自定义 GGPlot 图例

问题描述 投票:0回答:1

这是我写的一些简单的“R”代码:

library(ggplot2)

Year <- seq(from = 2010, to = 2024, by = 1)
IndoorCount <- round(runif(length(Year), 0, 50))
OutdoorCount <- round(runif(length(Year), 0, 50))
MyData <- data.frame(Year, IndoorCount, OutdoorCount)

# head(MyData)
# https://stackoverflow.com/questions/59794515/legends-in-ggplot

MyPlot <-
  ggplot(MyData, aes(x = Year)) +
  theme_minimal()+
  scale_x_continuous("Year", labels = MyData$Year, breaks = MyData$Year) +
  scale_y_continuous("Ride Count") +
  geom_line(aes(y = IndoorCount, color="red")) +
  geom_line(aes(y = OutdoorCount, color="green")) +
  scale_color_identity(guide = "legend")

它产生这个图表:

Graph with crummy legend

图例显示: 颜色

  • 绿色
  • 红色

如何生成显示以下内容的图例: 地点

  • 室内(红色)
  • 户外(绿色)

应该很简单吧?

我是否必须在 data.frame 中创建一个包含值(“室内”/“室外”)的位置列? 在我看来,这将是一种过于复杂的方法。

感谢您的所有指点/建议!

理查德

r ggplot2
1个回答
0
投票

只需使用

name
breaks
labels
scale_color_identity
参数即可:

MyPlot <-
  ggplot(MyData, aes(x = Year)) +
  theme_minimal()+
  scale_x_continuous("Year", labels = MyData$Year, breaks = MyData$Year) +
  scale_y_continuous("Ride Count") +
  geom_line(aes(y = IndoorCount, color="red")) +
  geom_line(aes(y = OutdoorCount, color="green")) +
  scale_color_identity(
    guide = "legend",
    name = "Location",
    breaks = c("red", "green"),
    labels = c("Indoor", "Outdoor")
  )

无需额外的列! labeled plot requested

© www.soinside.com 2019 - 2024. All rights reserved.