分别给出月份和年份时的ggplot直方图

时间:2018-12-27 07:17:52

标签: r ggplot2 histogram

我有以下数据框:

structure(list(NumOfEvents = c(989L, 989L, 1058L, 700L, 316L, 
1060L, 918L, 944L, 1022L, 1163L, 1094L, 1004L, 1041L, 1087L, 
1098L, 1013L, 1097L, 1274L, 1135L, 1018L, 1134L, 1183L, 1287L, 
1160L, 1146L, 1162L, 1209L, 1045L, 997L, 1502L, 1302L, 1214L, 
1156L, 1349L, 1301L, 1235L, 1180L, 1228L, 1424L, 1138L, 1278L, 
3363L, 3260L, 3481L, 3151L, 3070L, 2727L, 2359L, 2354L, 2333L, 
2215L), Year = c(1996L, 1996L, 1996L, 1996L, 1996L, 1997L, 1997L, 
1997L, 1997L, 1997L, 1997L, 1997L, 1997L, 1997L, 1997L, 1997L, 
1997L, 1998L, 1998L, 1998L, 1998L, 1998L, 1998L, 1998L, 1998L, 
1998L, 1998L, 1998L, 1998L, 1999L, 1999L, 1999L, 1999L, 1999L, 
1999L, 1999L, 1999L, 1999L, 1999L, 1999L, 1999L, 2000L, 2000L, 
2000L, 2000L, 2000L, 2000L, 2000L, 2000L, 2000L, 2000L), Month = c(5L, 
4L, 3L, 2L, 1L, 12L, 11L, 10L, 9L, 8L, 7L, 6L, 5L, 4L, 3L, 2L, 
1L, 12L, 11L, 10L, 9L, 8L, 7L, 6L, 5L, 4L, 3L, 2L, 1L, 12L, 11L, 
10L, 9L, 8L, 7L, 6L, 5L, 4L, 3L, 2L, 1L, 12L, 11L, 10L, 9L, 8L, 
7L, 6L, 5L, 4L, 3L)), row.names = c(NA, -51L), class = c("tbl_df", 
"tbl", "data.frame"))

我想在x轴上绘制月份和年份的直方图,以便对日期进行排序。我该怎么办?

2 个答案:

答案 0 :(得分:2)

这对您有用吗?

    library(lubridate)


        df %>% 
  mutate(Year=as.character(Year),Month=as.character(Month)) %>% 
  mutate(Date=as.character(make_date(Year,Month))) %>% 
  mutate(Date=str_remove_all(Date,"-01$")) %>% 
  arrange(Date) %>% 
  ggplot(aes(Date,NumOfEvents,fill=Year))+geom_col()+
  coord_flip()

您可以考虑选择特定年份。

答案 1 :(得分:1)

使用-

library(xts)
a <- xts(df$NumOfEvents, order.by=as.POSIXct(paste(df$Year,df$Month,"01",sep="/")))
plot.xts(a)

enter image description here

对于特定的直方图,将type参数作为h-

plot.xts(a,type = "h")

enter image description here