【问题标题】:seasonal ggplot in R?R中的季节性ggplot?
【发布时间】:2020-06-27 23:43:01
【问题描述】:

我正在查看从 11 月到 4 月的数据,并希望绘制从 11 月到 4 月的图。下面是我筛选出感兴趣月份的示例代码。

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)

我尝试从第 11 个月开始重新排序数据,然后是第 12 个月,然后是 01、02、03 和 04 月份。我使用了代码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)

现在,剧情从一月开始一直到十二月——我不想要这个。我想要从 11 月开始的情节,一直到 4 月。我尝试使用 scale_x_date(labels = date_format("%b", date_breaks = "month", name = "Month") 标记情节,但没有成功。任何帮助都会

【问题讨论】:

  • “现在,剧情从一月开始一直到十二月——我不想要这个。我想要从十一月开始的剧情,一直到四月。” i> 但你是facet_wrapping Year。您认为这会如何影响 11 月至 4 月的订单?

标签: r ggplot2 filter tidyverse axis-labels


【解决方案1】:

user2332849 答案很接近,但确实引入了错误。条形图的顺序不正确。例如,对于 2010 年,它显示的是年初数据之前的 11 月和 12 月的数据。为了以正确的顺序绘图,需要调整年份,以便日历从第 11 个月开始到第 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)

在下图中,2010 年的前 4 个月被转换为上一年的最后 4 个时期。 2011 年的最后 2 个月已经为 2012 年的前 4 个月做好了准备。

【讨论】:

  • 我正在查看季节性情节,在我的情况下,冬季从去年 11 月到次年 4 月开始。这意味着,我的一个完整的冬季是 2010 年 11 月至 12 月和 2011 年 1 月至 4 月。话虽如此,我应该在这里有一个季节,但我想看看我们如何根据我的定义重新排列数据季节。
  • @hydro,上面的情节就是这样做的。上面的 2010 年冬季是 2010 年 11 月至 12 月和 2011 年 1 月至 4 月的图。
【解决方案2】:

我在应用 factor() 之前将 Month 转换为字符并且它起作用了。

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)

输出:

【讨论】:

  • 注意,您的解决方案是乱序绘制月份。例如,2010 年 12 月绘制在 2010 年 1 月之前。
  • 是的,我只是保留了她的解决方案并改进了她的要求。她必须决定是否需要更好的布局。我同意这也不是理想的。
猜你喜欢
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
  • 2020-07-01
  • 1970-01-01
  • 2015-05-03
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多