在 r 中按年分面月度数据 - 没有数据出现的月份

faceting monthly data by year in r - months with no data appear

我正在尝试创建月度数据的分组条形图,这些数据是从多年的每日数据中汇总而来的。我已经通过分面实现了我想要的 x 轴,使用分面作为应用二次排序(按年和月)的方法。现在我已经按年分面,ggplot 显示所有月份 - 即使没有数据。这是在浪费 space 而我的实际数据集有多年的数据,我想添加标签,所以 space 是个问题。

如何在不浪费 space 的情况下完成此操作?有没有办法在不分面的情况下在 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 中有一种更优雅的方法可以做到这一点。我说的对吗?

关键是在facet_wrap()中使用scale = "free"。按照您的代码(经过修订),您将看到下图。

set.seed(222)
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)
mydf = data.frame(date,revenue,cost)

mydf$month <- month(mydf$date, label=TRUE) 
mydf$year <- year(mydf$date) 
mydf2 <- as.data.frame(ddply(mydf, .(month,year), numcolwise(sum)))

mydf3 <- melt(mydf2, id = c("month","year"))

ggplot(mydf3, aes(x=month, y=value, fill=variable)) +
geom_bar(stat = "identity", position = "dodge") +
facet_wrap(~ year, scale = "free")