Home > database >  Facet Wrap by Specific Variables ggplot2 r
Facet Wrap by Specific Variables ggplot2 r

Time:09-24

This is a tricky one, or at least it seems so to me...

I have a dataset that I need to facet wrap by specific variables. I want to group 2 variables, in this example Data1 Data2, on one side of the facet wrap with a stacked bar chart of pre and post... and on the other side a stacked bar chart of Data3 Data4.

In my example here, I have them all stacked with the fill set to pre and post but I can't find a method to separate them into further groups as mentioned above.

library(ggplot2)
library(reshape2)

df_dtype <- data.frame( Data_Type = c("Data1","Data2","Data3","Data4"),
                       Pre = c(150, 200, 325, 120),
                       Post = c(70,120,200,100) )

mdtype <- melt(df_date)
  
p <- ggplot(mdtype, aes(x=variable, y=value, fill=Data_Type))   
  geom_bar(position="stack", stat="identity")   
  ylab("Frequency")   xlab("")   ggtitle("Report Type")  
  theme(axis.ticks.x = element_blank(),axis.text.x = element_text(angle = 45, vjust = 1, hjust=1)) 
p

I'm sorry if this is unclear, feel free to ask for further information in the comments.

CodePudding user response:

mdtype$group = ifelse(mdtype$Data_Type %in% c("Data1", "Data2"),
                      "Group1", "Group2")

...
facet_wrap(~group)  
...

enter image description here

  • Related