I have a dataset which is this
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
)
I would like to create a time-series with just showing year in the y-Axis.
temperature$date = as.Date(paste(temperature$Year, temperature$Month,1), format = "%Y %m %d")
ggplot(temperature,
aes(
x = date,
y = Temperature
)) +
geom_line() +
ggtitle("Time series") +
xlab("Year") +
ylab("Temperature")
But the graph could not distinguish in the grid between months? how can I fix it?
This plot doesn’t have a grid with showing months. it looks really bad like this
>Solution :
Using scale_x_date you could set the date_breaks as well as the date_minor_breaks to achieve your desired result:
library(ggplot2)
ggplot(temperature,
aes(
x = date,
y = Temperature
)) +
geom_line() +
scale_x_date(date_breaks = "year", date_labels = "%Y", date_minor_breaks = "month") +
ggtitle("Time series") +
xlab("Year") +
ylab("Temperature")

