【问题标题】:Add custom slope and intercept to geom_smooth in R将自定义斜率和截距添加到 R 中的 geom_smooth
【发布时间】:2018-05-08 22:48:31
【问题描述】:

我正在尝试添加一条具有自定义截距和斜率的线。我知道我可以使用geom_abline,但这条线超出了绘图的边缘。 我有以下数据。

>table 
intent observed true
      0     0.00 0.07
  .1-.3     0.19 0.19
  .4-.6     0.51 0.41
  .7-.9     0.79 0.48
      1     1.00 0.53

这里是dput()

structure(list(intent = structure(c(4L, 1L, 2L, 3L, 5L), .Label = c(".1-.3", 
".4-.6", ".7-.9", "0", "1"), class = "factor"), observed = c(0, 
0.19, 0.51, 0.79, 1), true = c(0.07, 0.19, 0.41, 0.48, 0.53)), row.names = c(NA, 
-5L), class = "data.frame", .Names = c("intent", "observed", 
"true"))

这是我目前的解决方案

table %>% 
  ggplot(aes(y=true,x=observed))+
  geom_point()+
  geom_smooth(method = lm,se=F,color="black",lty=2,size=1/2)+
  geom_abline(intercept=0.07, slope=0.599,size=1/2)

问题在于geom_abline 是一种参考线。因此,它超过了 0 附近的绘图边缘,并且在 x 轴上超过 0.8 时不完全可见,这与 geom_smooth 在绘图区域中保留一条线相反。我怎样才能让我的geom_abline 在geom_smooth 中工作,使其适合绘图区域。

【问题讨论】:

  • 你能dput()你的数据吗?

标签: r ggplot2


【解决方案1】:

你可以使用geom_segment():

library(ggplot2)
  ggplot(table, aes(y = true, x = observed)) + 
  geom_point() + 
  geom_smooth(method = lm, se = F, color = "black", lty = 2, size = 1 / 2) + 
  geom_segment(x = 0, y = 0.07, xend = 1, yend = 0.669, size = 1 / 2) +
  scale_y_continuous(limits = c(0, 0.7))

用线性方程计算yend参数:y = 0.07 + x0.599

0.07 + 0.599
[1] 0.669

【讨论】:

  • 更新了我的答案,请查收。
  • 如果你在上面的代码中添加geom_abline(intercept=0.07, slope=0.599,size=1/2),你会看到这些行没有重叠。
  • 完美!我还添加了+ scale_y_continuous(limits = c(0,.7)),以便结束在 x=1
猜你喜欢
  • 2012-10-18
  • 2021-10-25
  • 1970-01-01
  • 2020-06-03
  • 1970-01-01
  • 2011-12-17
  • 1970-01-01
  • 2021-10-22
  • 2022-01-03
相关资源
最近更新 更多