我正在创建一个堆积的水平条形图。我似乎无法弄清楚如何对图例进行排序,因此蓝色是第一行,红色是最低行,同时在条形图中保持正确的顺序。这是我的代码:
library(tidyverse)
dat <- structure(list(prop_count = structure(6:1, .Label = c("Comparison Fail",
"Both Fail", "Bison Fail",
"Slower", "Indeterminant",
"Faster"), class = "factor"),
n = c(58L, 129L, 8L, 4L, 9L, 1L),
total = c(209, 209, 209, 209, 209, 209),
prop = c(0.277511961722488, 0.617224880382775,
0.0382775119617225, 0.0191387559808612,
0.0430622009569378, 0.00478468899521531),
pct_text = c("27.8%", "61.7%", "3.8%", "1.9%", "4.3%", "0.5%"),
plot_text = c("27.8% (58)", "61.7% (129)", "3.8% (8)", "1.9% (4)", "4.3% (9)", "0.5% (1)"),
rolling_prop = c(0.277511961722488, 0.894736842105263,
0.933014354066986, 0.952153110047847, 0.995215311004785, 1),
x_coord = c(0.138755980861244, 0.586124401913876, 0.913875598086124,
0.942583732057416, 0.973684210526316, 0.997607655502392)),
class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L))
dat
#> # A tibble: 6 x 8
#> prop_count n total prop pct_text plot_text rolling_prop x_coord
#> <fct> <int> <dbl> <dbl> <chr> <chr> <dbl> <dbl>
#> 1 Faster 58 209 0.278 27.8% 27.8% (5… 0.278 0.139
#> 2 Indeterminant 129 209 0.617 61.7% 61.7% (1… 0.895 0.586
#> 3 Slower 8 209 0.0383 3.8% 3.8% (8) 0.933 0.914
#> 4 Bison Fail 4 209 0.0191 1.9% 1.9% (4) 0.952 0.943
#> 5 Both Fail 9 209 0.0431 4.3% 4.3% (9) 0.995 0.974
#> 6 Comparison F… 1 209 0.00478 0.5% 0.5% (1) 1 0.998
plot_prop_bar <- function(dat){
run_colors <- RColorBrewer::brewer.pal(n = 3, name = "Blues")
failed_colors <- c("darkred", "red3", "red2")
dat %>%
ggplot(aes(x = "1", y = prop, fill = prop_count)) +
geom_bar(stat = "identity", position = position_stack(),
width = .3) +
coord_flip() +
scale_y_continuous(labels = scales::percent) +
scale_fill_manual(values = c(failed_colors, run_colors)) +
guides(fill = guide_legend(reverse = TRUE)) +
labs(x = "Assessments", y = "Proportion (Count)") +
theme(aspect.ratio = 1/3,
legend.position = "bottom",
legend.title = element_blank(),
axis.text.y = element_blank(),
axis.title = element_text(size = 15, face = "bold", color= "grey25"),
axis.text = element_text(size = 13),
legend.text = element_text(size = 14, face = "bold", color ="grey25"),
panel.grid.minor = element_blank())
}
plot_prop_bar(dat)
所需的输出将具有如下所示的图例:
Faster Indeterminate Slower
Bison Fail Both Fail Comparison Fail