ggplot2 - 如何并排绘制图形,只留下一个图例

时间:2017-08-01 03:28:22

标签: r ggplot2 graph position

基于下面的示例数据集,我试图制作2个图并将它们并排放置。我已尝试使用cowplot包来执行此操作。最后的输出非常混乱。

有没有办法可以将它们并排绘制,只显示1个图例,集中在底部(因为两个图形包含相同的元素)?

df <- data.frame(Year = c(rep(2012,5), rep(2016,5),
                          rep(2012,5), rep(2016,5),
                          rep(2012,5), rep(2016,5)),
                 Category = rep(c('A1','A2','A3','A4','A5'),6),
                 Group = rep(c('T1','T1','T1','T1','T1',
                           'T2','T2','T2','T2','T2',
                           'T3','T3','T3','T3','T3'),2),
                 Variable = runif(30,0,100))


plot2012 <- ggplot(df, aes(x = Group, y = Variable)) +
  geom_bar(aes(fill = Category), stat = 'identity') +
  ylim(0,500) +
  labs(y = 'Variable') +
  theme(legend.position = 'bottom',
        legend.title = element_blank(),
        axis.title = element_text(size = 10),
        legend.text = element_text(size = 10),
        axis.text = element_text(size = 10))

plot2016 <- ggplot(df, aes(x = Group, y = Variable)) +
  geom_bar(aes(fill = Category), stat = 'identity') +
  ylim(0,500) +
  labs(y = 'Variable') +
  theme(legend.position = 'bottom',
        legend.title = element_blank(),
        axis.title = element_text(size = 10),
        legend.text = element_text(size = 10),
        axis.text = element_text(size = 10))

欢迎格式/代码的任何其他一般性评论

1 个答案:

答案 0 :(得分:3)

您可以在facet_grid来电中添加ggplot

ggplot(df, aes(x = Group, y = Variable)) +
  geom_bar(aes(fill = Category), stat = 'identity') +
  ylim(0,500) +
  labs(y = 'Variable') +
  # Generate plots as panel based on Year
  facet_grid(. ~ Year) +
  theme(legend.position = 'bottom',
        legend.title = element_blank(),
        axis.title = element_text(size = 10),
        legend.text = element_text(size = 10),
        axis.text = element_text(size = 10))