【问题标题】:Adding a custom-range ab/smooth line to ggplot向 ggplot 添加自定义范围 ab/平滑线
【发布时间】:2014-03-18 12:40:55
【问题描述】:

有没有办法限制ggplot中斜线或平滑线的数据范围?例如,指数分布数据有时可能具有显着的领先异常值以及长但相当无趣的尾巴:

d = sort(rexp(100, rate = 1), decreasing=T) 
ggplot(NULL, aes(1:length(d), d)) + geom_point() + scale_y_log10() + geom_smooth(method = lm, se=F)

蓝线是 ggplot 的,我添加的红线是为了显示我想通过将 geom_smooth 函数约束到 12-80 的 x 范围来添加的线 - 例如显示其中的域在考虑特殊情况和长尾时,变量之间可能存在假设关系。任何关于如何实现这一点的建议表示赞赏。

【问题讨论】:

  • Illustrator 当然是一种选择,但如果让 geom_smooth 的 SE 对行动有信心,那就太好了

标签: r ggplot2


【解决方案1】:

试试这个:

library(ggplot2)
set.seed(1)
d <-  sort(rexp(100, rate = 1), decreasing=T)
gg <- data.frame(x=1:length(d),y=d
                 )
ggplot(gg, aes(x,y)) +
  geom_point() + 
  scale_y_log10() + 
  geom_smooth(data=gg[gg$x>11 & gg$x<81,],method = lm, se=F)

【讨论】:

  • 感谢。我确实尝试使用受限数据重复 aes 但失败了。不知道你可以管理这样的数据。
【解决方案2】:

不幸的是,我没有代表对@jlhoward 的帖子发表评论,但我想问一下以这种方式限制数据是否会影响回归线的结果? 通过子集,它是排除计算中的点还是只是对显示的结果产生影响?

例如,我希望执行以下操作:

# Adding "volume" to the diamonds data frame.
diamonds$volume = diamonds$x * diamonds$y * diamonds$z

ggplot(aes(x = volume, y = price), data = subset(diamonds, volume != 0 & volume < 800)) + 
  geom_point(alpha = 1/50, color = '#7ea4b3') + 
  geom_smooth(method = 'lm')

但是这条线比我想要的要长。我想在大约 x = 600 处切断线。

ggplot(aes(x = volume, y = price), data = subset(diamonds, volume != 0 & volume < 800)) + 
  geom_point(alpha = 1/50, color = '#7ea4b3') + 
  geom_smooth(data = subset(diamonds, volume > 0 & volume < 600),
              method = 'lm')

这是否会修改回归线的公式,是否可以检查公式是否已更改?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 2019-03-29
    • 2021-10-27
    • 1970-01-01
    相关资源
    最近更新 更多