简体   繁体   中英

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. My first guess was using a non-factor x aesthetic that controls the position along the x-axis of these box plots. However, once I try to do this it seems like geom_boxplot doesn't interpret the aesthetics as I would hope.

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.

Is there a way to control the x position of boxplots with ggplot2? 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.

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. However, I'm not sure why you cannot just pass x to the 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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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