gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 19:50:41 24 4
gpt4 key购买 nike

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

在这种情况下,左侧为“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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com