How to order x axis based on y axis values (in decreasing order)
Maybe this is what you are looking for. To order the bars in decreasing order without grouping by allele
you could add a helper variable via interaction
which could then be mapped on x
.
To only show the allele
on the x axis I make use of a custom labels function in scale_x_discrete
and use an underscore as separator in interaction.
library(ggplot2)
df$subject <- factor(df$subject, levels =c("her", "xan", "las", "reth"))
df$pososto = as.numeric(df$pososto)
df$x <- interaction(df$allele, df$subject, sep = "_")
ggplot(df, aes(x = reorder(x, -pososto), y = pososto, fill = subject)) +
geom_col(position = "dodge") +
scale_x_discrete(labels = ~ gsub("^(.*?)_.*$", "\\1", .x)) +
scale_fill_manual(values=c("#696969","#778899","#A9A9A9","#CCCCFF"))+
theme_bw(base_size = 9) +
geom_hline(yintercept = 0, colour = "black") +
theme(axis.text.x = element_text(angle = 60, hjust = 1))
Are you looking for such a solution?
library(tidyverse)
df %>%
arrange(allele, pososto, subject) %>%
group_by(allele) %>%
mutate(id=row_number()) %>%
mutate(subject = fct_reorder(allele, id)) %>%
ggplot(aes(x = allele, y = pososto, fill=factor(id))) +
geom_col(position=position_dodge())+
scale_x_discrete(limits = (unique(df$allele))) +
theme_bw(base_size = 9) +
geom_hline(yintercept = 0, colour = "black") +
scale_fill_manual(values=c("#696969","#778899","#A9A9A9","#CCCCFF"), labels = c("her", "reth", "las", "xan"))+
theme(axis.text.x = element_text(angle = 60, hjust = 1))
data:
df <- structure(list(allele = c("Ak24:02", "Ak24:02", "Ak24:02", "Ak24:02",
"Ak02:01", "Ak02:01", "Ak02:01", "Ak02:01", "Ak01:01", "Ak01:01",
"Ak01:01", "Ak01:01", "Ak11:01", "Ak11:01", "Ak11:01", "Ak11:01",
"Ak03:01", "Ak03:01", "Ak03:01", "Ak03:01", "Ak32:01", "Ak32:01",
"Ak32:01", "Ak32:01"), subject = c("her", "reth", "las", "xan",
"her", "reth", "las", "xan", "her", "reth", "las", "xan", "her",
"reth", "las", "xan", "her", "reth", "las", "xan", "her", "reth",
"las", "xan"), pososto = c(6.2076749, 0, 14.3529412, 0, -0.7751938,
0, -0.7751938, 0, 5.0666604, 0, 0, 11.944798, 0, 0, 9.7559913,
6.0631187, -12.4022258, -1.3476446, 13.1983584, 17.1626014, 0,
-13.1511297, 14.7583726, -5.6592186)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"
))