【问题标题】:How to smooth the line in R ggplot [duplicate]如何平滑R ggplot中的线条[重复]
【发布时间】:2018-01-16 02:45:14
【问题描述】:

我正在尝试将观察值作为点与预期值绘制成这样的线:

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')

这是正确的,但我希望线条平滑平滑(没有肘部)。将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)

【问题讨论】:

  • 似乎重复了,使用span 参数是解决方案吗? stackoverflow.com/questions/29038520/…
  • 不幸的是。我试过了。
  • 唯一有效的方法是使用任何预测方法来生成分数等级的预测。不确定这是否可能。这可能取决于您如何进行预测。无效的方法是使用样条几何。
  • @snoram 如果要求线穿过expected 列定义的特定点,则不是重复的。 OP 没有告诉我们,但在我看来,这是唯一有意义的方法。无论span 参数选择如何,geom_smooth() 都不会绘制插入特定点的线。
  • @striatum 您提供了一些其他详细信息作为对我答案的编辑。我把这些移到了你的问题中。

标签: r ggplot2


【解决方案1】:

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

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')

这种方法总是有效的,但我不喜欢用于数据可视化的样条曲线,因为它们构成了我们没有的数据。

我认为,更好的方法是插入分数等级的预测公式:

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')

【讨论】:

    猜你喜欢
    • 2023-01-12
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 2013-11-07
    • 1970-01-01
    • 2021-02-06
    相关资源
    最近更新 更多