【问题标题】:Get legend to display correctly using ggplot2使用 ggplot2 获取图例以正确显示
【发布时间】:2021-12-02 02:56:03
【问题描述】:

我想使用 ggplot 绘制观察值与拟合值;但是,我无法让传奇工作。它只报告观测值的条目,而不是拟合值。

我用 fpp2 的 iris 数据集重新创建了问题。

关于如何改进我的代码以包含拟合值的图例标题的任何建议?

data(iris)
fit = lm(Petal.Width ~ Petal.Length, data=iris)
fit = predict(fit)

ggplot(iris, aes(x = Petal.Length, y = Petal.Width, color = "red")) +
  geom_point() +
  geom_line(aes(y = fit), size = 1, color = "green") +
  scale_color_identity(name = "Legend",
                       breaks = c("red", "green"),
                       labels = c("Observed", "Fitted"),
                       guide = "legend")

【问题讨论】:

  • color = "green" 移动到aes()geom_line()

标签: r ggplot2 legend


【解决方案1】:

只需将color=green 移入geom_line() 的美学中。

library(datasets)
library(ggplot2)

data(iris)
fit = lm(Petal.Width ~ Petal.Length, data=iris)
fit = predict(fit)

ggplot(iris, aes(x = Petal.Length, y = Petal.Width, color = "red")) +
  geom_point() +
  geom_line(aes(y = fit), size = 1, color = "green") +
  scale_color_identity(name = "Legend",
                       breaks = c("red", "green"),
                       labels = c("Observed", "Fitted"),
                       guide = "legend")

作为说明,我可能还会考虑将“Fitted”更改为“Best Fit Line”或类似的东西,因为看到“observed”和“fitted”往往会让我想到residual analysis

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 2023-02-17
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多