2016-06-07 92 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

相关问题