[英]How to make a barplot in ggplot2 with both horizontal and vertical stacked bars?
我的數據框是這樣的:
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_PERCENTAGE
和C2_PERCENTAGE
。
我想使用ggplot2。 我使用了基本圖形,但這僅適用於C1_PERCENTAGE。
barplot(data$C1_PERCENTAGE, col = as.factor(data$GROUP)
這給出了C1_PERCENTAGE
。 我還希望這些欄旁邊還有C2_PERCENTAGE
。
我有兩個不同的變體。
首先,我們需要准備數據,(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")
多面條形圖
ggplot(ld, aes(x = id, y = value, fill = factor(GROUP))) +
geom_bar(stat = "identity", position = "stack") +
facet_wrap(~ variable, ncol = 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.