通过变量之一的值设置堆积条形图的顺序

ven*_*ion 4 r ggplot2

我被要求制作一个堆叠条形图,其中条形图和值以精确的方式堆叠和排序。

在这种情况下,左侧为“A3”,中间为“A2”,右侧为“A1”。我已经解决了。

让我感到困惑的是,我还被要求按“A1”的值对条形进行降序排序。在这种情况下,这意味着“值 11”出现在顶部,按顺序下降到“值 6”。条形的顺序记录在向量“plotOrder”中,我在下面的当前尝试中尝试使用它来实现某些目标。

在对 SO 上提出的有关订购堆叠条形图的许多问题进行搜索时,我没有找到描述或解决此特定问题的问题或答案。任何帮助将不胜感激。

下面的简化代码下载了一些与我目前正在使用的形式相同的随机数据,并生成了下面的图表。

library(ggplot2)

stackedBarPlot <- 
        ggplot(data) +
        aes(x = ValueName, y = Percent, fill = reorder(Response, plotOrder)) +
        geom_bar(position = "fill", stat = "identity") +
        coord_flip()
Run Code Online (Sandbox Code Playgroud)

产生这个图表:

在哪里

数据:

structure(list(ValueName = c("Value 11", "Value 14", "Value 13", 
"Value 12", "Value 10", "Value 1", "Value 5", "Value 9", "Value 4", 
"Value 7", "Value 8", "Value 3", "Value 15", "Value 2", "Value 6", 
"Value 11", "Value 14", "Value 13", "Value 12", "Value 10", "Value 1", 
"Value 5", "Value 9", "Value 4", "Value 7", "Value 8", "Value 3", 
"Value 15", "Value 2", "Value 6", "Value 11", "Value 14", "Value 13", 
"Value 12", "Value 10", "Value 1", "Value 5", "Value 9", "Value 4", 
"Value 7", "Value 8", "Value 3", "Value 15", "Value 2", "Value 6"
), plotOrder = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 
12L, 13L, 14L, 15L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 
11L, 12L, 13L, 14L, 15L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 
10L, 11L, 12L, 13L, 14L, 15L), Response = c("A1", "A1", "A1", 
"A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", 
"A1", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", 
"A2", "A2", "A2", "A2", "A2", "A3", "A3", "A3", "A3", "A3", "A3", 
"A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3"), Percent = c(86.5, 
85.3, 84.5, 83.2, 81, 79.5, 77, 76.7, 71, 66.2, 64.5, 60.5, 59.6, 
57.2, 53.2, 9.9, 9.4, 10.2, 9.9, 11.8, 14.7, 13.9, 13.5, 15.1, 
16.1, 21.3, 21.3, 26.6, 19.8, 18.5, 3.6, 5.3, 5.3, 6.9, 7.2, 
5.8, 9, 9.8, 13.9, 17.7, 14.1, 18.2, 13.8, 22.9, 28.2)), .Names = c("ValueName", 
"plotOrder", "Response", "Percent"), row.names = c(NA, -45L), class = c("tbl_df", 
"tbl", "data.frame"))
Run Code Online (Sandbox Code Playgroud)

预先感谢您提供的任何建议或解决方案。

Axe*_*man 5

通过预先计算一下顺序,这并不难:

library(magrittr)
library(dplyr)

o <- d %>% filter(Response == "A1") %>% arrange(Percent) %>% extract2("ValueName")

d %>% 
  mutate(ValueName = factor(ValueName, o)) %>% 
  ggplot() +
  aes(x = ValueName, y = Percent, fill = reorder(Response, plotOrder)) +
  geom_bar(position = "fill", stat = "identity") +
  coord_flip()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


And*_*tar 5

您已经拥有plotOrder,但您需要将其应用于重新排序x而不是fill...

stackedBarPlot <- 
  ggplot(data) +
  aes(x = reorder(ValueName,-plotOrder), 
      y = Percent, 
      fill = Response) +
  geom_bar(position = "fill", stat = "identity") +
  coord_flip()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • @M.Teich 这有点乱,但你可以将 `x` 美学更改为类似 `x = factor(ValueName,levels=ValueName[Response=="A1"][order(Percent[Response=="A1 "])])` (4认同)