【发布时间】:2013-10-07 13:44:34
【问题描述】:
我正在尝试按周和月绘制时间序列数据;理想情况下,我想,我想使用箱线图来可视化按周分类的每日数据。虽然我可以使用 scale_x_date 更改 x 轴上的标签和网格线,但这不会影响图中的点。
这是问题的演示和我当前(笨拙的)解决方案。
library(zoo)
library(ggplot2)
d = as.Date(c(as.Date("2007-06-01"):as.Date("2008-05-31"))) # using zoo to reformat numeric
x = runif(366, min = 0, max = 100)
df = data.frame(d,x)
# PROBLEM #
p = ggplot(df, aes(d, x))
p + geom_point()
p + geom_boxplot() # more or less useless
# CURRENT FIX #
df$Year.Month <- format(df$d, "%Y-%m")
p = ggplot(df, aes(Year.Month, x))
p + geom_point(alpha = 0.75)
p + geom_boxplot() # where I'm trying to get to...
我确信在ggplot 中有一种更优雅的方法可以做到这一点。我说的对吗?
@shadow 下面的回答要简洁得多。但是有没有办法使用分箱来做到这一点?也许以某种形式使用stats?
【问题讨论】:
-
你可以在
ggplot:p+geom_boxplot(aes(x=format(d, "%Y-%m")))做同样的事情 -
谢谢@shadow - 那更整洁了。
-
或者可能是影子代码的这种变化:
p + geom_boxplot(aes(format(as.yearmon(d)))) -
这很有趣——显然
as.yearmon没有按时间顺序返回该系列(我想知道为什么?)而且,它并不能完全让我读完每周一期——尽管我可能使用lubridate来实现同样的事情,也许?