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

标签 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()

产生这个图表:

Where

数据:
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"))

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

最佳答案

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

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

enter image description here

关于r - 通过变量之一的值设置堆积条形图的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44693075/

相关文章:

r - 根据定义的颜色代码为 ggplot 点着色

r - 在 r 中使用 ggplot2 创建散点图,其中 1 条回归线与所有点但点通过分组变量区分

R ggplot2 geom_rect 堆叠起来

r - 调整网格、相同大小的 ggplot2 图形之间的空间

r - 如何在 R 中读取大型 sas7bdat 数据集?

linux - R 将 tcpdump 输出设置为 fifo 然后变量或连接

R_LIBS_USER 被 R 忽略

r - 在ggplot2中的两个位置之间绘制曲线

r - conf.int 在 3.3 中不再使用 ggplot2、stat_summary

r - 如何使 ggplot2 在此图中排除零值?