我的问题是我想重新排序 ggplot 输出中的因素,使用 geom_bar(position = "fill"
生成),使得正类的最高比例最接近 y 轴。我已经设法找到了一个可行的解决方案,但从我的研究来看,似乎有一个更有效的解决方案潜伏着,尽管我似乎找不到它。
我已阅读问题 Order Bars in ggplot2 bar graph但我似乎找不到按比例排序的解决方案,即按数据框中未明确存在的值排序,但它们是摘要统计数据。
我看过Modifying Factor Order section of the book, R for Data Science并提出了一种解决方案,其中使用“prop”列生成摘要数据框,并使用 fct_reorder2()
根据这些值创建折线图。 。但是,我似乎无法将类似的逻辑应用于“填充”条形图。
我最终偶然发现的解决方案来自这个来源 #267 REORDER A VARIABLE IN GGPLOT2 ,您只需使用 mutate()
设置新的因子水平。然而,我并没有自己定义顺序,而是创建了一个数据框,根据正类的比例对因子进行排序。
我想知道是否有一种更有效的方法来做到这一点,也许是在一个长管道操作中?
这是一个可重现的示例:
library(ggplot2)
library(dplyr)
variable <- c(rep("alpha", 4),
rep("beta", 4),
rep("gamma", 4),
rep("delta", 4))
class <- c(rep("1", 4),
"1", "1", "0", "0",
rep("0", 3), "1",
rep("1", 3), "0")
dframe <- data.frame(variable, class)
plot_order <- dframe %>%
count(variable, class) %>%
group_by(variable) %>%
mutate(prop = prop.table(n)) %>%
filter(class == "1") %>%
arrange(prop)
lvls <- as.character(plot_order$variable)
dframe %>%
mutate(variable = factor(variable, levels = lvls)) %>%
ggplot(aes(x = variable, fill = class)) +
geom_bar(position ="fill") +
labs(y = "Proportion")
这是 plot_order
的输出:
# A tibble: 4 x 4
# Groups: variable [4]
variable class n prop
<fct> <fct> <int> <dbl>
1 alpha 1 4 1
2 delta 1 3 0.75
3 beta 1 2 0.5
4 gamma 1 1 0.25
结果:
带有基于位置“填充”的有序因子的条形图
提前致谢。
最佳答案
您可以使用 forcats
包中的 fct_reorder
。在您链接的第一个问题中也多次提到了这个包:
# data
dframe <- data.frame(
variable = rep(c("alpha", "beta", "gamma", "delta"), each = 4),
class = c(rep("1", 4),
"1", "1", "0", "0",
rep("0", 3), "1",
rep("1", 3), "0"))
dframe %>%
# convert variable to a factor, ordered (in descending order) by the proportion of
# rows where the class == "1"
mutate(variable = forcats::fct_reorder(.f = variable,
.x = class,
.fun = function(.x) mean(.x == "1"),
.desc = TRUE)) %>%
ggplot(aes(x = variable, fill = class)) +
geom_bar(position = "fill") +
labs(y = "Proportion")
关于r - 如何在 ggplot 中有效地按比例重新排序因子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55120534/