antR
antR

Reputation: 907

Merging separate Month and Year columns to graph in ggplot2

I've been around the forums looking for a solution to my issue but can't seem to find anything. Derivatives of my question and their answer haven't really helped either. My data has four columns, one for Year and one for Month). I've been wanting to plot the data all in one graph without using any facets for years in ggplot. This is what I've been struggling with so far with:

df<-data.frame(Month = rep(c("January", "February", "March", "April", "May", "June",
                         "July", "August", "September", "October", 
                         "November", "February", "March"),each = 20), 
           Year = rep(c("2018", "2019"), times = c(220, 40)), 
                      Type = rep(c("C", "T"), 260), 
                                 Value = runif(260, min = 10, max = 55))
df$Month<-ordered(df$Month, month.name)
df$Year<-ordered(df$Year)
ggplot(df) + 
  geom_boxplot(aes(x = Month, y = Value, fill = Type)) +
  facet_wrap(~Year)

I'd ideally like to manage this using dplyr and lubridate. Any help would be appreciated!

Upvotes: 2

Views: 1565

Answers (2)

LocoGris
LocoGris

Reputation: 4480

Do you mean this?

 df<-data.frame(Month = rep(c("January", "February", "March", "April", "May", "June",
                             "July", "August", "September", "October", 
                             "November", "February", "March"),each = 20), 
               Year = rep(c("2018", "2019"), times = c(220, 40)), 
               Type = rep(c("C", "T"), 260), 
               Value = runif(260, min = 10, max = 55))
df$Month <- factor(df$Month,levels=c("January", "February", "March", "April", "May", "June",
                             "July", "August", "September", "October", 
                                  "November", "Dicember"), ordered = T)
df$Month<-ordered(df$Month)
df$Year<-ordered(df$Year)
df$Year_Month <- paste0(df$Month, " ", df$Year)

df$Year_Month <- factor(df$Year_Month, levels = unique(df$Year_Month))

ggplot(df) + 
  geom_boxplot(aes(x = Year_Month, y = Value, fill = Type)) 

enter image description here

Upvotes: 0

MrFlick
MrFlick

Reputation: 206242

One option would be to make a true date value, then you can use the date axis formatter. Something like this is a rough start

ggplot(df) + 
  geom_boxplot(aes(x = lubridate::mdy(paste(Month, 1, Year)), y = Value, fill = Type, group=lubridate::mdy(paste(Month, 1, Year)))) + 
  scale_x_date(breaks="month", date_labels = "%m")

enter image description here

Upvotes: 4

Related Questions