每组放置多个箱形图分层

时间:2017-08-23 07:58:30

标签: r ggplot2

我有一个关于如何对每组制作多个箱形图进行分层的问题。这就是我的示例代码

library(ggplot2)

mtcars$vs <- as.character(as.numeric(mtcars$vs))

y6 <- ggplot(mtcars, aes(x=vs,y=hp)) +
  geom_boxplot(aes(group = vs),outlier.shape=NA, size=1, width = 0.6, fatten = 1) + 
  geom_jitter(aes(x=vs, y=hp, pch = factor(cyl)), position=position_jitter(width=.1, height=0), size = 2) + 
  scale_shape_manual(name ="X", values = c(1,2,3))  + 
  coord_cartesian(ylim=c(0, 350)) 

enter image description here

这是我从图中获得的。我希望通过图例对每个X轴的图形进行分层,共计6个箱形图(每个X轴3个;&#34; 1&#34; 3个&#34; 2&#34; 3个)。有没有办法做到这一点?我在下面附上了一张图片:

enter image description here

感谢您的想法!

2 个答案:

答案 0 :(得分:1)

以下是您的代码:

library(ggplot2)

ggplot(mtcars, aes(x=vs,y=hp,fill = factor(cyl))) +
  geom_boxplot(aes(fill = factor(cyl)),outlier.shape=NA, size=1, width = 0.6, fatten = 1) + 
  coord_cartesian(ylim=c(0, 350)) 

enter image description here

我在fill=中使用ggplot()参数按列cyl拆分/分组数据。

如果您仔细查看mtcars数据和情节,实际上cyl实际上没有vs = 1的3个唯一值,只有两个cyl 4&amp; 8)..因此你总共得到5盒

答案 1 :(得分:0)

这是你要问的吗?

//*[local-name()='cricketer']/name

enter image description here

ggplot(mtcars, aes(vs, hp)) + geom_boxplot() + facet_wrap(~cyl) + theme_bw() vs没有值,cyl==8vs只有一个值。

cyl==4

如果您喜欢着色图,可以使用table(mtcars$cyl, mtcars$vs) # 0 1 # 4 1 10 # 6 3 4 # 8 14 0 参数进行着色。

fill

enter image description here

相关问题