Merging separate Month and Year columns to graph in ggplot2

岁酱吖の 提交于 2021-01-28 01:41:04

问题


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!


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/55360812/merging-separate-month-and-year-columns-to-graph-in-ggplot2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!