【问题标题】:R - filling area to top of plot in ggplot2R - ggplot2中绘图顶部的填充区域
【发布时间】:2011-11-22 05:14:28
【问题描述】:

我正在 ggplot2 中创建一个填充密度的图,其中一些我想截断。我为缺少图片而道歉——显然我还不允许发布它们。一个简单的开头代码示例:

dd = with(density(rnorm(100,0,1)),data.frame(x,y))

ylimit = .3

ggplot(data = dd, mapping = aes(x = x, y = y), geom="line") +
 layer(data = dd, mapping = aes(x = x, y = y), geom = "area", 
       geom_params=list(fill="red",alpha=.3)) +
         scale_x_continuous(limits = c(-3,3)) +
         scale_y_continuous(limits = c(0,ylimit)) 

然而,这会导致填充密度中间的空白区域 dd$y > ylimit。

如果我用这个来补偿

dd$y = pmin(dd$y, ylimit)

该区域带有阴影,但绘图显示的区域略高于 ylimit,因此填充不会延伸到图的顶部。

理想情况下,我想知道如何让 ggplot 显示精确到 ylimit 的图,但欢迎使用任何其他将填充扩展到图顶部的解决方案。

编辑:修正了代码。

【问题讨论】:

  • 此代码对我不起作用。你能检查它并编辑吗?
  • 此链接也可能有助于演示 ggplot2 中“坐标”和“比例”之间的区别。 had.co.nz/ggplot2/coord_cartesian.html

标签: r ggplot2


【解决方案1】:

我想这就是你的意思。注意使用ifelse 来获取截断行为。

dd = with(density(rnorm(100,0,1)), data.frame(x, y))

ylimit = .3

dev.new(width=4, height=4)
ggplot(data = dd, mapping = aes(x = x, y = y), geom="line") +
 layer(data = dd, mapping = aes(x = x, y = ifelse(y>ylimit, ylimit, y)), geom = "area", 
       geom_params=list(fill="red",alpha=.3)) +
         scale_x_continuous(limits = c(-3,3)) +
         coord_cartesian(ylim=c(0, ylimit))

【讨论】:

  • 谢谢! Coord 正是我需要的,但似乎找不到。
  • @chris 这看起来非常复杂。你不能这样做:ggplot(dd,aes(x=x,y=y)) + geom_area(fill = "red",alpha = 0.3) + coord_cartesian(xlim = c(-3,3),ylim = c(0,0.3))
  • 是的,当然。 ggplot 有点新,所以我确定我正在使用一些非常尴尬的解决方法。感谢您的简单版本!
猜你喜欢
  • 1970-01-01
  • 2015-04-04
  • 1970-01-01
  • 2020-02-17
  • 1970-01-01
  • 2021-07-24
  • 1970-01-01
  • 2018-11-01
  • 2018-06-20
相关资源
最近更新 更多