r - ggplot 多线图上缺少图例

标签 r plot ggplot2 legend

我正在从包含每年最小值、平均值和最大值的数据框中逐年绘制年度温度数据。我一直无法在我的情节中找到传奇。理想情况下,图例应具有图例标题并将线条颜色标记为最小值、平均值和最大值。

如有任何帮助,我们将不胜感激。

数据看起来像(示例)并且数据被命名为“s”:

Example data

代码:

ggplot(s, aes(Year)) + 
geom_line(aes(y=min), color="blue") +
geom_line(aes(y=mean), color="green") + 
geom_line(aes(y=max), color="red") + 
ggtitle("Fort Collins Mean Annual Temperature") + 
ylab("Temperature (degF)")

剧情:

enter image description here

最佳答案

这里有一些与您的相似的可重现数据:

set.seed(123)
df1 <- data.frame(Year = 1893:1903, 
                  min  = sample(-5:10, 11, replace = TRUE), 
                  mean = sample(50:70, 11, replace = TRUE), 
                  max  = sample(90:100, 11, replace = TRUE), 
                  n    = sample(150:350, 11, replace = TRUE))

如果您将温度收集到一列中并按类型标记它们,则图例会自行处理。

library(tidyverse)
df1 %>% 
  gather(measurement, value, -n, -Year) %>% 
  ggplot(aes(Year, value)) + 
    geom_line(aes(group = measurement, color = measurement)) +
    scale_x_continuous(breaks = 1893:1903) +
    labs(y = "Temperature (F)", title = "Fort Collins Annual Temperature") + 
    theme_bw()

enter image description here

关于r - ggplot 多线图上缺少图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47128711/

相关文章:

r - 如何在ggplot2中将线从实线转换为点线

r - 数据表中不同变量的唯一观测数

R - 随着时间的推移可视化数据

r - ggplot时间序列间隔堆积条

r - 使用 knnImpute 时 preProcess() 中的 "Error: Must subset rows with a valid subscript vector"

r - 绑定(bind)不同长度的表

r - 如何更改马赛克图的调色板

r - scatter.smooth R 函数 - 颜色

r - 如何将 R ggplot 复制到剪贴板?

r - 在 plotly R 中包装 ggplot2 时图例中的额外变量