Multiple plots by factor in ggplot (facets)

穿精又带淫゛_ 提交于 2019-12-11 09:37:36

问题


I have a data frame with two qualitative variables (Q1, Q2) which are both measured on a scale of LOW, MEDIUM, HIGH and a continuous variable CV on a scale 0-100.

s = 5
trial <- data.frame(id = c(1:s), 
                Q1 = ordered(sample(c("LOW","MED","HIGH"),size=s,replace=T)), 
                Q2 = ordered(sample(c("LOW","MED","HIGH"),size=s,replace=T)), 
                CV = runif(s,0,100))

I need to use ggplot to show a faceted plot (preferably a horizontal boxplot/jitter) of the continous variable for each qualitative variable (x2) for each level (x3). This would result in a 3 x 2 layout.

As I'm very new to ggplot I'm unsure how this should be achieved. I've played with qplot and and can't work out how to control the facets to display both Q1 and Q2 boxplots on the same chart!!

Do I need to run multiple qplots to the same window (in base I would use par to control layout) or can it be achieved from a single command. Or should I try to melt the data twice?

trial = rbind(data.frame(Q = "Q1",Level = trial[,2], CV = trial[,4]),
          data.frame(Q = "Q2",Level = trial[,3], CV = trial[,4]))

I'll keep trying and hope somebody can provide some hints in the meantime.


回答1:


I'm not entirely clear on what you want, but maybe this helps:

ggplot(trial, aes(Level, CV)) + 
   geom_boxplot() + 
   geom_jitter() + 
   facet_wrap(~Q) + 
   coord_flip() 


来源:https://stackoverflow.com/questions/10987193/multiple-plots-by-factor-in-ggplot-facets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!