2017-08-01 84 views
2

基於下面的示例數據集,Iam試圖製作2個圖並將它們並排放置。我曾嘗試使用cowplot軟件包來執行此操作。最後的輸出非常混亂。ggplot2 - 如何繪製並排圖,只留下一個圖例

有沒有一種方法可以並排顯示它們,只顯示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)) 

任何其他一般性評論一個格式/代碼,歡迎

+0

順便說一句,'plot2012'和'plot2016'是一樣的。看起來你忘了按'Year'來設置'df'的子集。 – www

回答

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)) 
相關問題