stat_smooth和geom_ribbon之间的不良交互 [英] bad interaction between stat_smooth and geom_ribbon

查看:103
本文介绍了stat_smooth和geom_ribbon之间的不良交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在回答此问题,需要进行绘图平滑区域,但删除无用"区域.要在一个简单的geom_area(不平滑)上做到这一点,我只需将geom_ribbonaes(ymax=y, ymin=min(y))结合使用.但是将stat_smooth(geom="area")转换为stat_smooth(geom="ribbon", aes(ymax=y, ymin=min(y)))并不会产生预期的结果.

I was answering this question, which required plotting smooth areas, but removing 'useless' area. To do that on a simple geom_area (not smooth), i'd just use geom_ribbon with aes(ymax=y, ymin=min(y)). But turning a stat_smooth(geom="area") into a stat_smooth(geom="ribbon", aes(ymax=y, ymin=min(y))) does not yield the expected result.

geom_areageom_ribbon(末尾的虚拟数据):

geom_area to geom_ribbon (dummy data at the end):

ggplot(df, aes(x=x, y=y)) + geom_area()ggplot(df, aes(x=x, y=y)) + geom_ribbon(aes(ymax=y, ymin=min(y)))

现在是平滑版本:

ggplot(df, aes(x=x, y=y)) + stat_smooth(geom="area")ggplot(df, aes(x=x, y=y)) + stat_smooth(geom="ribbon", aes(ymax=y, ymin=min(y)))

我想要的输出是这样的:

The output that i wanted is something like this:

我发现了一些解决方案,其中包括使用平滑数据"制作一个新的数据帧,然后通常使用geom_ribbon对其进行绘制,但是仅当您具有已知功能并且可以轻松生成更多观察值时,该解决方案才适用.另一种尝试是将y限制设置为ylim(min(y), max(y)),但是ggplot不会绘制任何捕获"的几何图形.在一定程度上,所以也许如果有一种方法可以更改该功能,那将是解决我的问题的一种方法.

I found some solutions that involved making a new data frame with "smoothed data", and then plotting that normally with a geom_ribbon, but that applied only when you had a known function and could easily generate more observations. Another try was to set the y limits to ylim(min(y), max(y)), but ggplot doesn't plot any geom that is "caught" in a limit, so maybe if there's a way to change that feature it'd be a way to solve my problem.

虚拟数据:

df <- data.frame(
  x = 1:7,
  y = c(12.44, 11.98, 11.40, 12.15, 13.14, 11.99, 12.17))

推荐答案

您的意思是这样的吗?如果要在映射中使用计算出的变量,则需要用after_stat()对其进行换行. after_stat(y)表示使用由stat计算的y值,而不是原始数据帧中的y值."

Do you mean something like this? If you want to use a calculated variable in your mapping, you need to wrap it with after_stat(). after_stat(y) means "use the y value calculated by the stat, not the y value in the original data frame."

library(ggplot2)

df <- data.frame(
  x = 1:7,
  y = c(12.44, 11.98, 11.40, 12.15, 13.14, 11.99, 12.17)
)

ggplot(df, aes(x=x, y=y)) + 
  geom_point() +
  stat_smooth(
    geom="ribbon", 
    aes(ymax = after_stat(y), ymin = after_stat(min(y))),
    fill = "skyblue"
  )
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

reprex软件包(v0.3.0)创建于2020-10-28 sup>

Created on 2020-10-28 by the reprex package (v0.3.0)

这篇关于stat_smooth和geom_ribbon之间的不良交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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