百分比堆叠条形图

huangapple go评论61阅读模式
英文:

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 &lt;- 1:5
y1 &lt;- c(&quot;m&quot;, &quot;m&quot;, &quot;m&quot; ,&quot;m&quot;, &quot;n&quot;)
y2 &lt;- c(&quot;m&quot;, &quot;m&quot;, &quot;n&quot; ,&quot;n&quot;, &quot;p&quot;)
colors &lt;- c(&quot;m&quot; = &quot;red&quot;, &quot;n&quot; = &quot;green&quot;, &quot;p&quot; = &quot;blue&quot;)

what the plot should look like (ideally!) is the first row red-red-red-red-greenand stacked on this row red-red-green-green-blue and the lenght of each row is 1.

What I have so far is

df &lt;- data.frame(x = x, y1 = y1, y2 = y2)

colors &lt;- c(&quot;m&quot; = &quot;red&quot;, &quot;n&quot; = &quot;green&quot;, &quot;p&quot; = &quot;blue&quot;)

ggplot(df, aes(x = x)) +
  geom_bar(aes(fill = y1), position = &quot;stack&quot;, color = &quot;black&quot;) +
  geom_bar(aes(fill = y2), position = &quot;stack&quot;, color = &quot;black&quot;) +
  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 = &quot;black&quot;, position = position_stack(reverse = TRUE)) +
  scale_fill_manual(values = colors)

百分比堆叠条形图

huangapple
  • 本文由 发表于 2023年2月14日 20:35:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75447931.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定