将gridExtra和Facet_wrap / Facet_grid组合为双图表网格

时间:2015-09-23 09:01:01

标签: r ggplot2 gridextra

我需要在两个不同的折线图(非常不同的比例)上绘制两个指标。

使用gridExtra,我可以将其中一个放在另一个上面:

chart.top = ggplot(data=df, aes(x=Days, y=Estimated.revenue)) + geom_line()
chart.bottom = ggplot(data=df, aes(x=Days, y=Units.sold)) + geom_line()
chart = grid.arrange(chart.top,chart.bottom, heights = c(1/2, 1/2))

现在,我想使用facet_wrap / facet_grid创建这些双图表的网格,并使用其他维度(此处为品牌)拆分我的数据。可能吗?像下面这样的东西不起作用:

chart = grid.arrange(chart.top,chart.bottom, heights = c(1/2, 1/2)) + facet_wrap(~ Brands, ncol=3)

如果我做下面的事情,我最终会得到每个图表类型一个网格,而不是一个双图表网格:

chart.top = ggplot(data=df, aes(x=Days, y=Estimated.revenue)) + geom_line()
    + facet_wrap(~ Brands, ncol=3)
chart.bottom = ggplot(data=df, aes(x=Days, y=Units.sold)) + geom_line()
    + facet_wrap(~ Brands, ncol=3)
chart = grid.arrange(chart.top,chart.bottom, heights = c(1/2, 1/2))

编辑:

样本数据(dput(df)):

structure(list(Days = structure(c(16685, 16685, 16686, 16686, 
16687, 16687), class = "Date"), Brand = structure(c(1L, 2L, 1L, 
2L, 1L, 2L), .Label = c("Brand 2", "Brand 3"), class = "factor"), 
    Units.sold = c(145, 106, 1, 2, 2, 51), Estimated.revenue = c(0.073330174, 
    0.211338814, 0.000496881, 0.006588271, 0.001008714, 0.047465918
    )), .Names = c("Days", "Brand", "Units.sold", "Estimated.revenue"
), row.names = c(NA, -6L), class = "data.frame")

示例代码:

df = read.csv(file="rules_data2.csv", header=TRUE)
df$Estimated.revenue = as.numeric(gsub(",","", df$Estimated.revenue))
df$Units.sold = as.numeric(gsub(",","", df$Units.sold))
df$Days = as.Date(df$Days,"%m/%d/%Y")

#Option 1 - Work for one brand, showing 2 charts on top of each other
df1 = subset(df, Brand == "Brand 2")
chart.top = ggplot(data=df1, aes(x=Days, y=Units.sold)) +
  geom_line(size=1)
chart.bottom = ggplot(data=df1, aes(x=Days, y=Estimated.revenue)) +
  geom_line(size=1)
chart = grid.arrange(chart.top,chart.bottom, heights = c(1/2, 1/2)) 

选项1输出 Option 1 Output

#Option 2 - Show charts for my 2 brands but group them by metrics shown rather than Brand
chart.top = ggplot(data=df, aes(x=Days, y=Units.sold)) +
  geom_line(size=1) + facet_wrap(~ Brand, ncol=1)
chart.bottom = ggplot(data=df, aes(x=Days, y=Estimated.revenue)) +
  geom_line(size=1) + facet_wrap(~ Brand, ncol=1)
chart = grid.arrange(chart.top,chart.bottom, heights = c(1/2, 1/2)) 

选项2输出 Option 2 Output

1 个答案:

答案 0 :(得分:1)

从我的角度来看,grid.arrange在这里是多余的。 facet_grid全力以赴救援。

library(reshape2)
ggplot(data=melt(df, c("Days", "Brand")), aes(x=Days, y=value)) +
   geom_line(size=1) + 
   facet_grid(variable ~ Brand, scales = "free_y")

enter image description here