简体   繁体   English

合并单独的月份和年份列以在ggplot2中绘图

[英]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. 我一直想在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. 理想情况下,我想使用dplyr和lubridate进行管理。 Any help would be appreciated! 任何帮助,将不胜感激!

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

在此处输入图片说明

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM