2016-06-07 101 views
1

我的數據幀是這一個:如何在ggplot2中製作水平和垂直堆疊酒吧的barplot?

data <- data.frame("GROUP"= c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3), "C1_PERCENTAGE" = c(0, 10 ,22, 34, 37, 18, 24, 13), "C2_PERCENTAGE"=c(0, 8, 20, 24, 23, 11, 18, 9)) 

我想生產與堆疊條形柱狀圖水平基礎上GROUP,這樣將有三組棒水平。而垂直方向,我想堆疊基於C1_PERCENTAGEC2_PERCENTAGE的條形。

我想使用ggplot2。我使用了基礎圖形,但僅適用於C1_PERCENTAGE。

barplot(data$C1_PERCENTAGE, col = as.factor(data$GROUP) 

enter image description here

這給了情節C1_PERCENTAGE。我希望C2_PERCENTAGE也在這些酒吧旁邊。

+0

這是不是[瓷磚情節(http://docs.ggplot2.org/current/geom_tile.html)? – zx8754

+0

也許'barplot(「colnames < - 」(t(data)[ - 1,],data [,1]),在= TRUE旁邊)' – akrun

+0

[ggplot2 - Stacked Bar Chart](http:// stackoverflow問題/ 21236229/ggplot2-stacked-bar-chart) – theArun

回答

2

我有兩個不同的變體。首先我們需要準備數據,(a)添加id,(b)重塑爲長格式。

準備數據

library(data.table) 
d <- data.table(
    "id" = 1:24, 
    "GROUP" = c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3), 
    "C1_PERCENTAGE" = c(0, 10 ,22, 34, 37, 18, 24, 13), 
    "C2_PERCENTAGE"=c(0, 8, 20, 24, 23, 11, 18, 9) 
) 
ld <- melt(d, id.vars = c("id", "GROUP")) 

堆積條形圖

library(ggplot2) 
ggplot(ld, aes(x = id, y = value, fill = variable)) + 
    geom_bar(stat = "identity", position = "stack") 

enter image description here

刻麪條形圖

ggplot(ld, aes(x = id, y = value, fill = factor(GROUP))) + 
    geom_bar(stat = "identity", position = "stack") + 
    facet_wrap(~ variable, ncol = 1) 

enter image description here

+0

@technOslerphile感謝您接受我的回答 - 但是兩個變體中的哪一個最終確實回答了您的問題/符合您的要求。謝謝。 – Uwe

+0

不得不編輯facetted條形圖的代碼以匹配圖 – Uwe