0

I have been trying to make a stacked barplot on a set of thematic variables:

Theme 1 <- c(0,1,1,0,0,1,2,2,1,0)
Theme 2 <- c(0,1,0,1,0,1,2,2,0,1)
Theme 3 <- c(2,2,0,1,0,1,0,1,1,1)
Theme 3 <- c(0,0,0,1,1,1,1,2,2,0)

where: 0 = No, 1 = Yes and 2 = Missing

I want to make a stacked plot of these themes are against different regions in my dataframe, so I can see which regions focus on what themes.

list of regions:

Region_abb <- c(ESA, WCA, MENA, ASIA)

I have tried making a matrix:

Themes_matrix <- matrix(c(Theme 1), nrow = length(Theme 1))

(Themes_matrix_app <- cbind(Themes_matrix, Theme 2, Theme 3, Theme 4)) 

(## But now I am missing Theme 1 as name in my matrix!, how do I get it back?)

barplot(Themes_matrix_app, main = "Theme Overview", 
        xlab = "Themes", 
        col=c("darkblue","orange", "red"), #representing the different levels for my theme variables
        legend = rownames(Themes_matrix_app))

(##But this doesn't plot the different levels (0,1,2) and everything is in black!)

So I tried:

p2 <- ggplot (data = MY_df, aes(Themes_matrix_app, value = Themes_matrix_app, fill = Region_abb))+
  geom_bar(stat="identity")

(## This just flat out didn't work)

My goal is reaching what was portrayed on: How to plot an histogram in R with several variables?

I have tried coping the coding from the first example, but I just didn't get it.

I hope that my fairly long question makes sense and that someone can help me move on from here.

Thank you

0

2 Answers 2

1

Here is an answer using ggplot2. First to use ggplot your data needs to bee in tidy format (https://cran.r-project.org/web/packages/tidyr/vignettes/tidy-data.html). So using the data you provided:

library(tidyverse)
df <- data.frame(Q = 1:10, Theme1 = c(0,1,1,0,0,1,2,2,1,0),
Theme2 = c(0,1,0,1,0,1,2,2,0,1),
Theme3 = c(2,2,0,1,0,1,0,1,1,1),
Theme4 = c(0,0,0,1,1,1,1,2,2,0))
tidy_df <- df %>% 
  gather(key = "Theme", value = "Answer", 2:5)

Then plotting the data using ggplot:

ggplot(data = tidy_df, aes(x = Theme , fill = as.factor(Answer)))+
  geom_bar()

stacked bar plot

Sign up to request clarification or add additional context in comments.

Comments

0

Here's a base r option:

out <- do.call(rbind,lapply(list(Theme1,Theme2,Theme3,Theme4),table))
rownames(out) <- c("T1","T2","T3","T4")
barplot(t(out))

Beautify to your hearts content

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.