【发布时间】:2015-05-12 13:23:07
【问题描述】:
我正在尝试创建一个从每日数据汇总多年的月度数据分组条形图。我已经从我的 x 轴上完成了我想要的分面,使用分面作为一种应用二次排序的方式(按年和月)。现在我已经按年分面,ggplot 显示所有月份 - 即使没有数据。这是浪费空间,我的实际数据集有多年的数据,我想添加标签,所以空间是个问题。
如何在不浪费空间的情况下完成此任务?有没有办法在 x 轴上添加二级排序(年、月)而不用刻面?
# create data set
date = seq(as.Date("2014-05-01"),as.Date("2015-05-10"), "day")
revenue = runif(375, min = 0, max = 200)
cost = runif(375, min = 0, max = 100)
df = data.frame(date,revenue,cost)
head(df)
# adding month and year column, then aggregating to monthly revenue and cost
library(plyr)
df$month <- month(df$date, label=TRUE)
df$year <- year(df$date)
df <- as.data.frame(ddply(df, .(month,year), numcolwise(sum)))
# melting the data for a 'grouped chart' in ggplot
library(reshape)
df <-melt(df, id = c("month","year"))
#create chart
library(ggplot2)
g <-ggplot(df, aes(x=month, y=value, fill=variable))
g + geom_bar(stat="identity", position="dodge") + facet_wrap(~ year)
我确信在 ggplot 中有一种更优雅的方法可以做到这一点。我说的对吗?
【问题讨论】:
-
第一行之后:"as.Date.numeric(c(as.Date("2014-05-01"):as.Date("2015-05-10")) 中的错误) : 'origin' 必须提供"
-
你可以试试
facet_wrap(~ year, scale = "free") -
@jazzurro 谢谢!那解决了它。有没有办法选择你的答案作为解决方案?
-
我会发给你的。完成。