2
votes

I'm ploting annual temperature data by year from a dataframe that contains the minimum, mean and maximum values for each year. I've been unable to get a legend on my plot. Ideally, the legend should have a Legend title and label the line colors as Min, Mean and Max.

Any help would be appreciated.

The data looks like (example) and the data is named "s":

Example data

The code:

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)")

The Plot:

enter image description here

1
Please provide the data as plain text, not an image. You'll find this much easier with all the temperatures in one column and the type (min, mean, max) in another. - neilfws

1 Answers

2
votes

Here's some reproducible data that resembles yours:

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))

If you gather the temperatures into one column and label them by type, the legend takes care of itself.

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