这是我写的一些简单的“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")
它产生这个图表:
图例显示: 颜色
如何生成显示以下内容的图例: 地点
应该很简单吧?
我是否必须在 data.frame 中创建一个包含值(“室内”/“室外”)的位置列? 在我看来,这将是一种过于复杂的方法。
感谢您的所有指点/建议!
理查德
只需使用
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")
)