使用 ggplot 按月显示条形图总计?
我有时间序列数据(我已将其作为 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 有一种“更简单”的方法。
I have time series data (I've posted it here as a 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")
What's the best way to plot this as a bar plot in ggplot that would show the total value per month (with the month name as text)?
I can do this manually by adding a month field:
x$month <- format(x$date, format="%B")
ddply(x, .(month), function(x) sum(x[, "data"]))
Then plotting this independently, but the months are not ordered correctly using this approach (suppose that I need to create an ordered factor?); I am also presuming that there's an "easier" way with ggplot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我绝不是时间序列数据方面的专家,但这段代码对我有用:
根据我的建议,您最终会用一条线突出显示零,并且 y 轴围绕 0 对称。我更改了 x 轴次要网格线到“月”,因为每个月的条形在每个方向上延长了几周,这对于数据的聚合方式实际上没有意义。
编辑:
当然,大部分代码只是为了创建每月的总和。如果您的日期数据采用日期格式,则日期刻度将自动用于轴。要更改主要的 x 中断及其格式,可以使用
scale_x_date()
进行操作,请参阅
?strftime
了解有关格式字符串含义的详细信息。I am by no means an expert with time series data, but this code worked for me:
With my suggestions, you end up highlighting zero with a line, and the y-axes are symmetrical around 0. I changed the x-axis minor gridlines to "month", because the bar for each month extended a few weeks in each direction, which isn't actually meaningful for how the data is aggregated.
Edit:
Of course, most of this code was just to create the monthly sums. If your date data is in a date format, the date scales are automatically used for the axes. To change up the major x breaks and their format, you do so with
scale_x_date()
See
?strftime
for details on what the format strings mean.