【问题标题】:faceting monthly data by year in r - months with no data appear以 r 年按年分面月度数据 - 没有数据出现的月份
【发布时间】: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 谢谢!那解决了它。有没有办法选择你的答案作为解决方案?
  • 我会发给你的。完成。

标签: r ggplot2


【解决方案1】:

关键是在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")

【讨论】:

    猜你喜欢
    • 2017-11-05
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 2022-11-17
    相关资源
    最近更新 更多