Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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?

like image 989
Kevin Ushey Avatar asked Jan 25 '13 19:01

Kevin Ushey


People also ask

What variables does Stat_boxplot () Compute?

Computed variables stat_boxplot() provides the following variables, some of which depend on the orientation: width. width of boxplot. ymin or xmin.

How does Ggplot deal with outliers?

We can remove outliers in R by setting the outlier. shape argument to NA. In addition, the coord_cartesian() function will be used to reject all outliers that exceed or below a given quartile. The y-axis of ggplot2 is not automatically adjusted.

Does Ggplot boxplot show median or mean?

A boxplot summarizes the distribution of a continuous variable and notably displays the median of each group.


1 Answers

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)
like image 116
Didzis Elferts Avatar answered Sep 18 '22 13:09

Didzis Elferts