r - 如何平滑R ggplot中的线条

标签 r ggplot2

这个问题在这里已经有了答案:





plotting smooth line through all data points

(1 个回答)


6 个月前关闭。




我试图将观察到的值绘制为与预期值相对的点,如下所示:

d <- data.frame(
    ranks = 1:9,
    observed = c(0.736, 0.121, 0.067, 0.034, 0.026, 0.015, 0.001, 0.001, 0.000),
    expected = c(0.735, 0.136, 0.051, 0.025, 0.015, 0.009, 0.006, 0.005, 0.003)
)

ggplot(d, aes(x=ranks, y=observed)) +
  geom_point(size=2.2) +
  geom_line(aes(x=ranks, y=expected), size=0.8, colour='red')

enter image description here

这是正确的,但我更希望线条很好地平滑(没有肘部)。使用 geom_smooth()loessgam并没有真正帮助,因为两者都过度平滑(以不同的方式)。有什么建议吗?

更新:如果这很有用,以下是我生成预期值的方式:
# BACIS POWER FUNCTION:
fPow <- function(x, a, b) {a * x^b}

# INITIALIZE PARAMETERS:
est1 <- coef(nls(observed ~ fPow(ranks, a, b),
    start=c(a=1, b=1), data=d))

# FITTING:
nlfit1 <- nls(observed ~ fPow(ranks, a, b),
    start=est1, data=d)

# EXPECTED VALUES:
expected <- predict(nlfit1)

最佳答案

您可以尝试的一种解决方案是强制通过预期点的样条:

library(ggplot2)
library(ggalt)

d <- data.frame(
  ranks = 1:9,
  observed = c(0.736, 0.121, 0.067, 0.034, 0.026, 0.015, 0.001, 0.001, 0.000),
  expected = c(0.735, 0.136, 0.051, 0.025, 0.015, 0.009, 0.006, 0.005, 0.003)
)

ggplot(d, aes(x = ranks, y = observed)) +
  geom_point(size = 2.2) +
  geom_xspline(aes(y = expected), size = 0.8,
               spline_shape = -.15, colour = 'red')

enter image description here

这种方法总是有效,但我不是数据可视化样条的忠实粉丝,因为它们构成了我们没有的数据。

我认为,更好的方法是插入分数等级的预测公式:
fPow <- function(x, a, b) {a * x^b}
est1 <- coef(nls(observed ~ fPow(ranks, a, b),
                 start=c(a=1, b=1), data=d))
nlfit1 <- nls(observed ~ fPow(ranks, a, b),
              start=est1, data=d)

d2 <- data.frame(ranks = seq(1, 9, by = 0.1))
expected <- predict(nlfit1, d2)
d2 <- data.frame(d2, expected)

ggplot(d, aes(x = ranks, y = observed)) +
  geom_point(size = 2.2) +
  geom_line(data = d2, aes(x = ranks, y = expected), size = 0.8, colour = 'red')

enter image description here

关于r - 如何平滑R ggplot中的线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48252789/

相关文章:

r - 使用 ggcorrplot 包更改相关图对角线的方向

r - 如何使用 h2o.predict 预测时间序列的 future 值

r - 使用 mutate_at 时在函数中使用变量名

r - 哪些 R 对象可以具有任意属性?

r - 在ggplot2中注释轴

r - 对齐单独绘图的尺寸

r - ggplot2 ggsave 文本大小没有改变

r - 当 RStudio 绘图 Pane 处于事件状态时,ggsave() 中绘图的缩放比例不同

r - Packrat损坏R功能时出现问题

r - 标签与背景对比 : determine if color is light or dark