This is my dataset:
temperature <- data.frame(
stringsAsFactors = FALSE,
Year= c(1998,1998,1998,1998,1998,1998,1998,1998,1998,1998,1998,1998,1999,1999,1999,1999,1999,1999,1999,1999,1999,1999,1999,1999,2000,2000,2000,2000,2000,2000,2000,2000,2000,2000,2000,2000,2001,2001,2001,2001,2001,2001,2001,2001,2001,2001,2001,2001,2002,2002,2002,2002,2002,2002,2002,2002,2002,2002,2002,2002),
Month = c(1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12),
Temperature = c(5,6,7,12,15,16,27,28,22,10,11,6,6,6,7,13,16,15,25,26,24,12,11,4,5,6,7,12,15,17,28,30,22,10,11,7,7,7,7,12,18,17,25,24,20,3,3,4,5,6,7,12,15,16,27,28,22,10,11,6),
check.names = FALSE
)
temperature$date = as.Date(paste(temperature$Year, temperature$Month,1), format = "%Y %m %d")
This is the code I used
ggplot(temperature,
aes(
x = date,
y = Temperature,
colour=as.factor(Month),
group=1
)) +
geom_line() +
ggtitle("Time series") +
scale_x_date(
date_breaks = "year",
date_labels = "%Y",
date_minor_breaks = "month"
) +
xlab("Year") +
ylab("Temperature")
Now the months were in number and not in name
I used that code
ggplot(temperature,
aes(
x = date,
y = Temperature,
colour=as.factor(Month),
group=1
)) +
geom_line() +
ggtitle("Time series") +
scale_x_date(
date_breaks = "year",
date_labels = "%Y",
date_minor_breaks = "month", labels=month.abb
) +
xlab("Year") +
ylab("Temperature")
But seems not work. I thougt that I have to change something in scale_x_date?
How can I change that month names came into the legend?
The problem is that the legend shows month number instead of month name
>Solution :
For a color scale, I would specify the labels when you convert month to factor:
ggplot(temperature,
aes(
x = date,
y = Temperature,
colour=factor(Month, levels = 1:12, labels = month.abb),
group=1
)) +
geom_line() +
ggtitle("Time series") +
scale_x_date(
date_breaks = "year",
date_labels = "%Y",
date_minor_breaks = "month"
) +
labs(
x = "Year",
y = "Temperature",
color = "Month"
)
