r - ggplot2: plotting time series data by month & week -
i'm trying plot time series data week , month; ideally, think, i'd use boxplots visualise daily data binned week. while can change labels , gridlines on x-axis using scale_x_date, won't affect points in plot.
here's demonstration of problem , current (clumsy) solution.
library(zoo) library(ggplot2) d = as.date(c(as.date("2007-06-01"):as.date("2008-05-31"))) # using zoo 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() # i'm trying to... i feel there's more elegant way within ggplot. right?
@shadow's answer below neater. there way using binning? using stats in form, perhaps?
you can treat dates dates in r, , use scale_x_date() in ggplot x-labels want.
also, find easier create new variable-factor called "month" group boxplots month. in case used lubridate accomplish task.
if not want go through trouble of creating new variable "month", bloxplot plotted on 15th of month, making viz reading bit 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")
if not create variable "month", boxplots won't align nicely x tick marks:


Comments
Post a Comment