'facet grid to split the ggplot bar plot by group
I want to draw a bar plot using ggplot, with reorder the variables based on each group and split the gg bar plot by the groups. Here a samples example.
M <- data.frame(group = c(rep("A", 3), rep("B",4), rep("C", 2)), values = runif(9,-3,4), names = paste0("G", seq(1,9)))
ggplot(M) +
theme_minimal() +
aes(x = reorder(names,values), y = values, fill = factor(sign(values))) +
geom_bar(stat="identity", width = 0.5, show.legend = T, alpha = 0.75, position=position_dodge()) +
scale_fill_manual(values=c('mediumorchid4', 'goldenrod')) +
ggtitle("") +
theme(axis.text.y = element_text(size = "12", face = "bold"),
plot.title = element_text(face = "bold" , size = 10)) +
xlab("Names") +
ylab("Values") +
geom_hline(yintercept = 0, size = 1, color = "black") +
coord_flip()
For this example, I want to reorder the samples based on each group, then split horizontally by the groups, and the bar colors adjust by the sign of the values to different colors. Thank you.
Solution 1:[1]
It sounds like you are looking for something like this:
ggplot(M) +
theme_minimal() +
aes(x = reorder(names, values), y = values, fill = factor(sign(values))) +
geom_bar(stat="identity", width = 0.5, show.legend = TRUE, alpha = 0.75,
position=position_dodge()) +
scale_fill_manual(values=c('mediumorchid4', 'goldenrod')) +
ggtitle("") +
theme(axis.text.y = element_text(size = "12", face = "bold"),
plot.title = element_text(face = "bold" , size = 10)) +
xlab("Names") +
ylab("Values") +
geom_hline(yintercept = 0, size = 1, color = "black") +
coord_flip() +
facet_grid(group~., space = "free_y", scales = "free_y", drop = TRUE)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Allan Cameron |

