R 如何在ggplot2中使用水平和垂直堆叠条制作条形图?

R 如何在ggplot2中使用水平和垂直堆叠条制作条形图?,r,ggplot2,geom-bar,R,Ggplot2,Geom Bar,我的数据框是这样的: 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)) 这给出了C1\u百分比的曲线图。我想在这些条旁边加上C2\u百分比 我有两种不同的变体 首先,我们需要准备数

我的数据框是这样的:

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))


这给出了
C1\u百分比的曲线图。我想在这些条旁边加上
C2\u百分比

我有两种不同的变体

首先,我们需要准备数据,(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)

这不是吗?可能是
条形图(“Colnames此链接的可能副本应可用这不是我想要的。请参阅edit@technOslerphile感谢您接受我的回答-但这两个变体中的哪一个最终回答了您的问题/满足了您的要求。谢谢。必须编辑刻面条形图的代码以匹配图形
ggplot(ld, aes(x = id, y = value, fill = factor(GROUP))) + 
  geom_bar(stat = "identity", position = "stack") +
  facet_wrap(~ variable, ncol = 1)