如何在 ggplot2 中使用水平和垂直堆叠条形图制作条形图?
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)reshape为long格式。
准备数据
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)
我的数据框是这个:
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)reshape为long格式。
准备数据
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)