Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change x axis limits when using factor for geom_boxplot

Tags:

r

ggplot2

Is it possible to increase the x axis limits by 1 on both sides when using factors as your x-axis scale. For instance, in the following plot is it possible to change the xlimits to 3 and 9? i.e. xlim(3,9)

p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot()

When trying xlim() I get:

Error: Discrete value supplied to continuous scale

And when I try scale_x_continuous(limits = c(3,9)) I get:

Error in if (zero_range(from) || zero_range(to)) return(rep(mean(to),  : 
  missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In loop_apply(n, do.ply) :
  no non-missing arguments to min; returning Inf
2: In loop_apply(n, do.ply) :
  no non-missing arguments to max; returning -Inf
3: In loop_apply(n, do.ply) :
  position_dodge requires constant width: output may be incorrect
like image 614
Getch Avatar asked Sep 01 '25 16:09

Getch


1 Answers

you want scale_x_discrete:

p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot() + scale_x_discrete(limits = c("4","6"))

or xlim:

p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot() + xlim("4", "6")

Edit: asked to include wider range. To include other values, you need to use the breaks function, on a list of factors:

p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot() +
    scale_x_discrete(breaks = factor(3:9), limits = c("3", "4", "5", "6", "7", "8", "9"))

In this case, you will have to plot out the 8 cyl boxplot, unless you give a fake 8:

p + geom_boxplot() +
  scale_x_discrete(breaks=factor(c("3","4","5","6","7", "eight", "9")),
                   limits = c("3", "4", "5", "6", "7", "eight", "9") 

or filter it out before plotting:

mtcars<-mtcars[mtcars$cyl!=8,]

Reference: scale_x_discrete

like image 112
jeremycg Avatar answered Sep 04 '25 07:09

jeremycg