【问题标题】:Legends in ggplotggplot 中的图例
【发布时间】:2020-01-17 20:35:50
【问题描述】:

我正在尝试绘制这些数据,折线图是正确的,但我无法显示图例。有什么想法吗?

ggplot(data, aes(x=time_months, size=I(1))) +geom_line(aes(y=monthly_net_revenue, color=I("blue"))) +
    geom_line(aes(y=cumsum(discounted_monthly_net_revenue), color=I("purple"))) +
    geom_line(aes(y=monthly_expenses, color=I("red"))) +
    geom_line(aes(y=cumsum(monthly_revenue), color=I("green")))

【问题讨论】:

  • 如果您包含一个简单的reproducible example 以及可用于测试和验证可能的解决方案的示例输入,则更容易为您提供帮助。现在我们看不到你的情节是什么样的

标签: r ggplot2 legend


【解决方案1】:

这可能对你有用

ggplot(data, aes(x=time_months, size=I(1))) +
    geom_line(aes(y=monthly_net_revenue, color="blue")) +
    geom_line(aes(y=cumsum(discounted_monthly_net_revenue), color="purple")) +
    geom_line(aes(y=monthly_expenses, color="red")) +
    geom_line(aes(y=cumsum(monthly_revenue), color="green")) + 
    scale_color_identity(guide = "legend")

scale_color_identity() 将您传递给color= 的值直接用作颜色,而不是将它们视为组名。这种方法不需要I()

【讨论】:

  • 不确定 OP 是否需要它,但也许您可以添加参数 guide = "legend" 来显示图例。
  • @markus 你建议把那个参数放在哪里?如果这样做,指南不会自动显示吗?
  • scale_color_identity() 中的默认值为 guide = "none" - 这完全有道理,但 OP 表示他们无法显示图例。这就是我发表评论的原因。
  • @markus 啊。我明白你在说什么。是的。忘记那个细节了。当包含样本数据时,测试会容易得多!
最近更新 更多