seasonal ggplot in R?

强颜欢笑 提交于 2021-02-08 08:17:00

问题


I am looking at data from Nov to April and would like to have a plot starting from Nov to April. Below is my sample code to screen out month of interests.

library(tidyverse)
mydata = data.frame(seq(as.Date("2010-01-01"), to=as.Date("2011-12-31"),by="days"), A = runif(730,10,50))
colnames(mydata) = c("Date", "A")
DF = mydata %>%
     mutate(Year = year(Date), Month = month(Date), Day = day(Date)) %>%
     filter(Month == 11 | Month == 12 | Month == 01 | Month == 02 | Month == 03 | Month == 04)

I tried to re-order the data starting at month 11 followed by month 12 and then month 01,02,03,and,04. I used the code factor(Month, levels = c(11,12,01,02,03,04)) along with the code above but it didn't work. I wanted a plot that starts at month Nov and ends on April. The following code gave me attached plot

ggplot(data = DF, aes(Month,A))+
  geom_bar(stat = "identity")+ facet_wrap(~Year, ncol = 2)

Right now, the plot is starting at January all the way to December- I dont want this. I want the plot starting at November, and all the way to April. I tried to label the plot using scale_x_date(labels = date_format("%b", date_breaks = "month", name = "Month") which didn't work. Any help would


回答1:


I converted Month to character before applying factor() and it worked.

DF = mydata %>%
  mutate(Year = year(Date), Month = month(Date), Day = day(Date)) %>%
  filter(Month %in% c(11, 12, 1, 2, 3, 4)) %>%
  mutate(Month = sprintf("%02d", Month)) %>%
  mutate(Month = factor(Month, levels = c("11","12","01","02","03","04")))

ggplot(data = DF, aes(Month,A))+
  geom_bar(stat = "identity")+ facet_wrap(~Year, ncol = 2)

Output:




回答2:


user2332849 answer is close but does introduce an error. The bar are not in the correct order. For example for 2010, it plot is showing November and December's data prior to the beginning of the year's data. In order to plot in the proper order the year will need adjustment so that the calendar starts on month 11 and goes to month 4.

#Convert month to Factor and set desired order
DF$Month<- factor(DF$Month, levels=c(11, 12, 1, 2, 3, 4))
#Adjust the year to match the year of the beginning of series
#For example assign Jan, Feb, Mar and April to prior year
DF$Year<-ifelse(as.integer(as.character(DF$Month)) <6, DF$Year-1, DF$Year)

#plot
ggplot(data = DF, aes(Month,A))+
  geom_bar(stat = "identity") + 
  facet_wrap(~Year, ncol = 3)

In the plot below the first 4 months of 2010 is shifted to become the last 4 periods of the prior year. And the last 2 months of 2011 is ready for the first 4 months of 2012.



来源:https://stackoverflow.com/questions/60713132/seasonal-ggplot-in-r

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