Ggplot2: display time series by month and week

I am trying to record time series data for weeks and months; Ideally, I think I would like to use the boxes to visualize the daily data associated with the week. Although I can change the labels and grid lines along the x axis using scale_x_date , this will not affect the points on the graph.

This demonstrates the problem and my current (awkward) solution.

 library(zoo) library(ggplot2) d = as.Date(c(as.Date("2007-06-01"):as.Date("2008-05-31"))) # using zoo to reformat numeric x = runif(366, min = 0, max = 100) df = data.frame(d,x) # PROBLEM # p = ggplot(df, aes(d, x)) p + geom_point() p + geom_boxplot() # more or less useless # CURRENT FIX # df$Year.Month <- format(df$d, "%Y-%m") p = ggplot(df, aes(Year.Month, x)) p + geom_point(alpha = 0.75) p + geom_boxplot() # where I'm trying to get to... 

I am sure there is a more elegant way to do this from ggplot . I'm right?

@shadow the answer below is far ahead. But is there a way to do this using binning? Using stats in some way, maybe?

+6
source share
1 answer

You can treat Dates as dates in R and use scale_x_date () in ggplot to get the x-labels you need.

  • In addition, itโ€™s easier for me to simply create a new variable factor called โ€œMonthโ€ to group the boxes by month. In this case, I used lubridate to complete the task.

  • If you donโ€™t want to worry about creating a new โ€œMonthโ€ variable, your bloxplot will be displayed on the 15th of the month, which makes reading more difficult.

     library(magrittr) library(lubridate) library(dplyr) df %>% mutate(Date2 = as.Date(paste0("2000-", month(d), "-", "01"))) %>% mutate(Month = lubridate::month(d)) %>% ggplot(aes(Date2, x, group=Month)) + geom_boxplot() + scale_x_date(date_breaks="1 month", date_labels = "%b") 

enter image description here

If you do not create the Month variable, the boxes will not align well with the x tick marks:

enter image description here

+1
source

Source: https://habr.com/ru/post/955410/


All Articles