How to place multiple boxes in one column using ggplot (geom_boxplot)

I would like to build a box in which 4 factors (N1: N4) overlap in one column. For example, with the following data:

df<-data.frame(N=N,Value=Value) Q<-c("C1","C1","C2","C3","C3","C1","C1","C2","C2","C3","C3","Q1","Q1","Q1","Q1","Q3","Q3","Q4","Q4","Q1","Q1","Q1","Q1","Q3","Q3","Q4","Q4") N<-c("N2","N3","N3","N2","N3","N2","N3","N2","N3","N2","N3","N0","N1","N2","N3","N1","N3","N0","N1","N0","N1","N2","N3","N1","N3","N0","N1") Value<-c(4.7,8.61,8.34,5.89,8.36,1.76,2.4,5.01,2.12,1.88,3.01,2.4,7.28,4.34,5.39,11.61,10.14,3.02,9.45,8.8,7.4,6.93,8.44,7.37,7.81,6.74,8.5) 

with the following (regular) code, the output is 4 squares displayed in 4 columns for 4 variables

 ggplot(df, aes(x=N, y=Value,color=N)) + theme_bw(base_size = 20)+ geom_boxplot() 

thank you very much

0
source share
1 answer

Updated Answer

Based on your comment, you can add marginal boxes here. We will use the mtcars built-in data mtcars .

Firstly, some tweaking:

 library(cowplot) # Common theme elements thm = list(theme_bw(), guides(colour=FALSE, fill=FALSE), theme(plot.margin=unit(rep(0,4),"lines"))) 

Now create three graphs:

 # Main plot p1 = ggplot(mtcars, aes(wt, mpg, colour=factor(cyl), fill=factor(cyl))) + geom_smooth(method="lm") + labs(colour="Cyl", fill="Cyl") + scale_y_continuous(limits=c(10,35)) + thm[-2] + theme(legend.position = c(0.85,0.8)) # Top margin plot p2 = ggplot(mtcars, aes(factor(cyl), wt, colour=factor(cyl))) + geom_boxplot() + thm + coord_flip() + labs(x="Cyl", y="") # Right margin plot p3 = ggplot(mtcars, aes(factor(cyl), mpg, colour=factor(cyl))) + geom_boxplot() + thm + labs(x="Cyl", y="") + scale_y_continuous(limits=c(10,35)) 

Lay out the graphs and add the legend:

 plot_grid(plotlist=list(p2, ggplot(), p1, p3), ncol=2, rel_widths=c(5,1), rel_heights=c(1,5), align="hv") 

enter image description here

Original answer

You can stack all four boxes in one column, but the graph will be unreadable. The first example below removes N as the x coordinate, but retains N as a color aesthetic. This causes the four N levels to appear at the same mark (which I removed by setting breaks to NULL ). However, the plots still evade. To build them on top of each other, set the slope width to zero, as I did in the second example. However, graphs are not readable when they overlap.

 ggplot(df, aes(x="", y=Value,color=N)) + theme_bw(base_size = 20) + geom_boxplot() + scale_x_discrete(breaks=NULL) + labs(x="") ggplot(df, aes(x="", y=Value,color=N)) + theme_bw(base_size = 20) + geom_boxplot(position=position_dodge(0)) + scale_x_discrete(breaks=NULL) + labs(x="") 

enter image description here

+2
source

Source: https://habr.com/ru/post/1257469/


All Articles