Currently, I have to hard code the labels within scale_x_discrete() but I need to dynamically create a subset of them and have them in descending order with additional labels added to the bottom of the y-axis that have static locations.
library(dplyr) library(ggplot2) library(scales) set.seed(1) samp <- data.frame(Names = sample(paste0("Sample_", 1:5), 90, replace = TRUE), Mode = rep(c("UN", "CN", "CF"), 150)) ggplot(samp, aes(x=Names)) + geom_bar(aes(fill=Mode), position="fill", width = .5) + scale_fill_manual(values = c("#a0de6f","tan1","#DAEBFF")) + scale_y_continuous(label=percent, expand = c(0,0)) + coord_flip() + labs(fill="", x="", y="") + theme_minimal() + theme( legend.position = "bottom", plot.margin = unit(c(1,1,.5,0),"cm"), legend.key.size = unit(.5, "lines") ) + guides(fill = guide_legend(reverse = TRUE)) + scale_x_discrete("", labels= c( bquote("Sample_5" * " (n = " * .(sum(samp$Names == "Sample_5")) * ")"), bquote(italic("Sample_1") * " (n = " * .(sum(samp$Names == "Sample_1")) * ")"), bquote(italic("Sample_3") * " (n = " * .(sum(samp$Names == "Sample_3")) * ")"), bquote(italic("Sample_4") * " (n = " * .(sum(samp$Names == "Sample_4")) * ")"), bquote(italic("Sample_2") * " (n = " * .(sum(samp$Names == "Sample_2")) * ")"))) This bit:
scale_x_discrete("", labels= c( bquote("Sample_5" * " (n = " * .(sum(samp$Names == "Sample_5")) * ")"), bquote(italic("Sample_1") * " (n = " * .(sum(samp$Names == "Sample_1")) * ")"), bquote(italic("Sample_3") * " (n = " * .(sum(samp$Names == "Sample_3")) * ")"), bquote(italic("Sample_4") * " (n = " * .(sum(samp$Names == "Sample_4")) * ")"), bquote(italic("Sample_2") * " (n = " * .(sum(samp$Names == "Sample_2")) * ")"))) Is what I need to be dynamically created and put in descending order by count but I don't really know how.
How it should look:
