如何使用ggplot2不对称地扩展坐标轴而不手动设置限制? [英] How to expand axis asymmetrically with ggplot2 without setting limits manually?

查看:893
本文介绍了如何使用ggplot2不对称地扩展坐标轴而不手动设置限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望barplot的底部轴线为零,但顶部扩大了一小部分(根据某个比例)。不过,我正在绘制 stat_summary 的输出,因此我没有可用的最大值,并且使用 scale =free_y 所以我不能手动设置它们。否则,我会使用 baptiste添加 geom_blank 的技巧。我知道我可以读取这些值并手动创建一个带有上限的数据框,但是可以在不对限制进行硬编码的情况下进行设置?

另一个选择是计算函数调用之外的方法,并且只需调用 stat_summary (this例如:



pre> ggplot(mtcars)+
stat_summary(aes(cyl,mpg),
fun.y =mean,
geom =bar )+
scale_y_continuous(expand = c(0,0))+
facet_grid(carb〜。,free_y)


解决方案

您可以通过创建自定义类的scale来扩展ggplot,并像这样实现内部S3方法scale_dimension: b
$ b

  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 _ ...
class(s​​)< - c('custom_expand',class(s​​))
s
}
pre>

这也是覆盖默认比例的一个例子。现在,为了得到想要的结果,你可以像这样扩展:

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

列表中的向量是乘法因子,第二个是加法部分,每个向量的第一个(第二个)元素对应于下(上)边界。

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

解决方案

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.

这篇关于如何使用ggplot2不对称地扩展坐标轴而不手动设置限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆