Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a time series with the months in the background grid

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The picture is this
enter image description here

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading