英文:
Percent stacked barchart
问题
我正在尝试在R中使用ggplot2
创建一个堆叠条形图。
例如,对于这组数据:
x <- 1:5
y1 <- c("m", "m", "m", "m", "n")
y2 <- c("m", "m", "n", "n", "p")
colors <- c("m" = "red", "n" = "green", "p" = "blue")
理想情况下,图表应该如下所示:第一行为red-red-red-red-green
,并在其上方叠加red-red-green-green-blue
,每行的长度为1。
到目前为止,我有以下代码:
df <- data.frame(x = x, y1 = y1, y2 = y2)
colors <- c("m" = "red", "n" = "green", "p" = "blue")
ggplot(df, aes(x = x)) +
geom_bar(aes(fill = y1), position = "stack", color = "black") +
geom_bar(aes(fill = y2), position = "stack", color = "black") +
scale_fill_manual(values = colors)
但输出结果是下面这样的,不符合预期:
请问有谁能提供帮助吗?
英文:
I am trying to create a stacked bar plot using ggplot2
in R
.
For example, for this data
x <- 1:5
y1 <- c("m", "m", "m" ,"m", "n")
y2 <- c("m", "m", "n" ,"n", "p")
colors <- c("m" = "red", "n" = "green", "p" = "blue")
what the plot should look like (ideally!) is the first row red-red-red-red-green
and stacked on this row red-red-green-green-blue
and the lenght of each row is 1.
What I have so far is
df <- data.frame(x = x, y1 = y1, y2 = y2)
colors <- c("m" = "red", "n" = "green", "p" = "blue")
ggplot(df, aes(x = x)) +
geom_bar(aes(fill = y1), position = "stack", color = "black") +
geom_bar(aes(fill = y2), position = "stack", color = "black") +
scale_fill_manual(values = colors)
but the output is
which is not what we are looking for.
Could someone help please?
答案1
得分: 1
以下是您要翻译的代码部分:
ggplot(tidyr::pivot_longer(df, -x), aes(x = x)) +
geom_bar(aes(fill = value, group = interaction(name, value)),
color = "black", position = position_stack(reverse = TRUE)) +
scale_fill_manual(values = colors)
英文:
It's easier to do this if you pivot your data into long format, and use a single geom_bar
with a reversed stack:
ggplot(tidyr::pivot_longer(df, -x), aes(x = x)) +
geom_bar(aes(fill = value, group = interaction(name, value)),
color = "black", position = position_stack(reverse = TRUE)) +
scale_fill_manual(values = colors)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论