百分比堆叠条形图

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

Percent stacked barchart

问题

我正在尝试在R中使用ggplot2创建一个堆叠条形图。

例如,对于这组数据:

  1. x <- 1:5
  2. y1 <- c("m", "m", "m", "m", "n")
  3. y2 <- c("m", "m", "n", "n", "p")
  4. colors <- c("m" = "red", "n" = "green", "p" = "blue")

理想情况下,图表应该如下所示:第一行为red-red-red-red-green,并在其上方叠加red-red-green-green-blue,每行的长度为1。

到目前为止,我有以下代码:

  1. df <- data.frame(x = x, y1 = y1, y2 = y2)
  2. colors <- c("m" = "red", "n" = "green", "p" = "blue")
  3. ggplot(df, aes(x = x)) +
  4. geom_bar(aes(fill = y1), position = "stack", color = "black") +
  5. geom_bar(aes(fill = y2), position = "stack", color = "black") +
  6. scale_fill_manual(values = colors)

但输出结果是下面这样的,不符合预期:

百分比堆叠条形图

请问有谁能提供帮助吗?

英文:

I am trying to create a stacked bar plot using ggplot2 in R.

For example, for this data

  1. x &lt;- 1:5
  2. y1 &lt;- c(&quot;m&quot;, &quot;m&quot;, &quot;m&quot; ,&quot;m&quot;, &quot;n&quot;)
  3. y2 &lt;- c(&quot;m&quot;, &quot;m&quot;, &quot;n&quot; ,&quot;n&quot;, &quot;p&quot;)
  4. 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

  1. df &lt;- data.frame(x = x, y1 = y1, y2 = y2)
  2. colors &lt;- c(&quot;m&quot; = &quot;red&quot;, &quot;n&quot; = &quot;green&quot;, &quot;p&quot; = &quot;blue&quot;)
  3. ggplot(df, aes(x = x)) +
  4. geom_bar(aes(fill = y1), position = &quot;stack&quot;, color = &quot;black&quot;) +
  5. geom_bar(aes(fill = y2), position = &quot;stack&quot;, color = &quot;black&quot;) +
  6. scale_fill_manual(values = colors)

but the output is
百分比堆叠条形图
which is not what we are looking for.

Could someone help please?

答案1

得分: 1

以下是您要翻译的代码部分:

  1. ggplot(tidyr::pivot_longer(df, -x), aes(x = x)) +
  2. geom_bar(aes(fill = value, group = interaction(name, value)),
  3. color = "black", position = position_stack(reverse = TRUE)) +
  4. 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:

  1. ggplot(tidyr::pivot_longer(df, -x), aes(x = x)) +
  2. geom_bar(aes(fill = value, group = interaction(name, value)),
  3. color = &quot;black&quot;, position = position_stack(reverse = TRUE)) +
  4. 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:

确定