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

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

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") 

回答1:

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 

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!