简体   繁体   English

如何在ggplot2中控制箱线图的x位置?

[英]How can I control the x position of boxplots in ggplot2?

First, a quick example to set the stage: 首先,设置阶段的快速示例:

set.seed(123)
dat <- data.frame( 
  x=rep( c(1, 2, 4, 7), times=25 ), 
  y=rnorm(100), 
  gp=rep(1:2, each=50) 
)

p <- ggplot(dat, aes(x=factor(x), y=y))
p + geom_boxplot(aes(fill = factor(gp)))

I would like to produce a similar plot, except with control over the x position of each set of boxplots. 我想制作一个类似的情节,除了控制每组箱图的x位置。 My first guess was using a non-factor x aesthetic that controls the position along the x-axis of these box plots. 我的第一个猜测是使用非因子x美学控制沿着这些箱形图的x轴的位置。 However, once I try to do this it seems like geom_boxplot doesn't interpret the aesthetics as I would hope. 然而,一旦我尝试这样做,似乎geom_boxplot并不像我希望的那样解释美学。

p + geom_boxplot( aes(x=x, y=y, fill=factor(gp)) )

In particular, geom_boxplot seems to collapse over all x values in some way when they're non-factors. 特别是,当geom_boxplot是非因素时,它们似乎以某种方式折叠所有x值。

Is there a way to control the x position of boxplots with ggplot2? 有没有办法用ggplot2控制箱线图的x位置? Either through specifying a distance between each level of a factor aesthetic, some more clever use of non-factor aesthetics, or otherwise? 要么通过指定因子美学的每个层次之间的距离,要么更巧妙地使用非要素美学,否则?

You can use scale_x_discrete() to set positions (ticks) for the x axis. 您可以使用scale_x_discrete()来设置x轴的位置(刻度)。

p <- ggplot(dat, aes(x=factor(x), y=y))
p + geom_boxplot(aes(fill = factor(gp))) + 
    scale_x_discrete(limits=1:7)

You can also do this with the group aesthetic. 您也可以使用group美学来做到这一点。 However, I'm not sure why you cannot just pass x to the group . 但是,我不确定为什么你不能只将x传递给该group This doesn't work: 这不起作用:

ggplot() + 
  geom_boxplot(data=dat, aes(x=x, y=y, fill=factor(gp), group=x))

But this does: 但这样做:

ggplot() + 
  geom_boxplot(data=dat, aes(x=x, y=y, fill=factor(gp), group=paste(x, gp)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM