简体   繁体   English

在r-月份中按年份对月度数据进行分面,没有数据出现

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

I'm trying to create a grouped bar chart of monthly data, aggregated from daily data, over multiple years. 我正在尝试创建多个年度的月度数据的分组条形图,这些数据是根据每日数据汇总的。 I have accomplished what I wanted from my x-axis from faceting, using faceting as a way to apply a secondary sort (on year and month). 我已经使用多面体作为一种应用次级排序(按年和月)的方式,从多面体的X轴实现了我想要的。 Now that I've faceted by year, ggplot is showing all months - even when there's no data. 既然我已经了解了年份,ggplot将显示所有月份-即使没有数据也是如此。 This is wasting space and my actual data set has years of data and I want to add labels, so space is an issue. 这浪费了空间,而我的实际数据集包含数年的数据,并且我想添加标签,因此空间是一个问题。

How can I accomplish this without the wasted space? 如何在不浪费空间的情况下完成此任务? Is there a way to add the secondary sort (year,month) on the x-axis without faceting? 有没有一种方法可以在x轴上添加次要排序(年,月)而无需多面化?

ggplot示例

# 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)

I feel certain that there's a more elegant way to do this from within ggplot. 我确信在ggplot中有一种更优雅的方法可以做到这一点。 Am I right? 我对吗?

The key is to use scale = "free" in facet_wrap() . 关键是在facet_wrap()使用scale = "free" By following your code (with a revision), you'll see the graphic below. 通过遵循您的代码(带有修订版),您将看到下面的图形。

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")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM