代码之家  ›  专栏  ›  技术社区  ›  Omry Atia

分别给出月份和年份时,绘制柱状图

  •  0
  • Omry Atia  · 技术社区  · 6 年前

    我有以下数据框:

    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 回复  |  直到 6 年前
        1
  •  2
  •   NelsonGon phoxis    6 年前

    这对你有用吗?

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

    你可以考虑选择具体的年份。

        2
  •  1
  •   Vivek Kalyanarangan    6 年前

    使用-

    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