Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expand axis asymmetrically with ggplot2 without setting limits manually?

Tags:

r

ggplot2

I want the bottom axis for a barplot to be zero, but top expanded by a small amount (according to some scale). However, I am plotting the output of stat_summary so I do not have the maximum value available to me, and I am using facets with scale="free_y" so I cannot manually set them. Otherwise I would use baptiste's trick of adding geom_blank. I know I could read off the values and create a data frame with upper bounds manually, but can this be set without having to hard-code the limits?

The other option is to compute the means outside of the function call and just plot that without calling stat_summary (this way I have the upper bounds directly for each facet), but is there any way around this?

Example:

ggplot(mtcars)+
  stat_summary(aes(cyl,mpg),
               fun.y="mean",
               geom="bar")+
  scale_y_continuous(expand=c(0,0))+
  facet_grid(carb~.,"free_y")
like image 941
hatmatrix Avatar asked Mar 18 '14 12:03

hatmatrix


People also ask

How do I increase y axis limit in R?

To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.

How do I change the Y axis scale in ggplot2?

Use scale_xx() functions It is also possible to use the functions scale_x_continuous() and scale_y_continuous() to change x and y axis limits, respectively.

What is scaling in ggplot2?

Scales in ggplot2 control the mapping from data to aesthetics. They take your data and turn it into something that you can see, like size, colour, position or shape. They also provide the tools that let you interpret the plot: the axes and legends.


1 Answers

You can "extend" ggplot by creating a scale with a custom class and implementing the internal S3 method scale_dimension like so:

library("scales")
scale_dimension.custom_expand <- function(scale, expand = ggplot2:::scale_expand(scale)) {
  expand_range(ggplot2:::scale_limits(scale), expand[[1]], expand[[2]])
}

scale_y_continuous <- function(...) {
  s <- ggplot2::scale_y_continuous(...)
  class(s) <- c('custom_expand', class(s))
  s
}

This is also an example of overriding the default scale. Now, to get the desired result you specify expand like so

qplot(1:10, 1:10) + scale_y_continuous(expand=list(c(0,0.1), c(0,0)))

where the first vector in the list is the multiplicative factor, the second is the additive part and the first (second) element of each vector corresponds to lower (upper) boundary.

like image 53
Rosen Matev Avatar answered Sep 28 '22 12:09

Rosen Matev