【问题标题】:Barplot totals by month with ggplot?用ggplot按月统计条形图?
【发布时间】:2011-03-30 14:52:21
【问题描述】:

我有时间序列数据(我已将其作为 data.frame 发布在这里):

x <- structure(list(date = structure(c(1264572000, 1266202800, 1277362800, 
1277456400, 1277859600, 1278032400, 1260370800, 1260892800, 1262624400, 
1262707200), class = c("POSIXt", "POSIXct"), tzone = ""), data = c(-0.00183760994446658, 
0.00089738603087497, 0.000423513598318936, 0, -0.00216496690393131, 
-0.00434836817931339, -0.0224199153445617, 0.000583823085470003, 
0.000353088613905206, 0.000470295331234771)), .Names = c("date", 
"data"), row.names = c("1", "2", "3", 
"4", "5", "6", "7", "8", "9", "10"
), class = "data.frame")

在 ggplot 中将其绘制为条形图的最佳方法是什么,以显示每月的总值(以月份名称作为文本)?

我可以通过添加月份字段来手动执行此操作:

x$month <- format(x$date, format="%B")
ddply(x, .(month), function(x) sum(x[, "data"]))

然后独立绘制,但使用这种方法没有正确排序月份(假设我需要创建一个有序因子?);我还假设 ggplot 有一种“更简单”的方式。

【问题讨论】:

    标签: r ggplot2 time-series


    【解决方案1】:

    我绝不是时间序列数据方面的专家,但这段代码对我有用:

    #The binning by month, saving as a date
    x$month <- as.Date(cut(x$date, breaks = "month"))
    
    #Plotting
    p <- ggplot(x, aes(month, data))+
         stat_summary(fun.y = sum, geom = "bar")
    
    #My suggestions for display
    minmax <- max(abs(x$data))
    
    p + geom_hline(y = 0)+
        scale_x_date(minor = "month")+
        ylim(-minmax, minmax)
        # or more ggplot2 accurately
        #+coord_cartesian(ylim = c(-minmax, minmax))
    

    根据我的建议,您最终会用一条线突出显示零,并且 y 轴围绕 0 对称。我将 x 轴小网格线更改为“月”,因为每个月的条形图在每个方向,这对于数据的聚合方式实际上没有意义。

    编辑: 当然,大部分代码只是为了创建每月总和。如果您的日期数据采用日期格式,则日期刻度会自动用于轴。要更改主要的 x 中断及其格式,请使用 scale_x_date()

    p + scale_x_date(major = "month", format = "%b")
    #or
    p + scale_x_date(major = "month", format = "%B %Y")
    

    有关格式字符串含义的详细信息,请参阅?strftime

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多