I want to reorder the following barplot by Group1 (G1), so that the country with the highest count in G1 is first ...
I have tried a lot of things, but nothing works - it seems like it is reordering the values by the sum of G1 and G2, but all I need is want is to reorder it by G1.
Any suggestions out there?
Here some sample data:
country <- c("DE","DE","FR", "FR", "PL","PL")
Variable <- c("G1", "G2","G1","G2", "G1", "G2")
Value <- c(24,25,6,55,12,20)
df <- data.frame(country, Variable, Value)
And this is the plot I have so far:
ggplot(data = df,
aes(reorder(country,-Value), Value, fill=Variable))
geom_bar(position="dodge", stat="identity")
Which looks like this:
It tried converting it to factors, reordering, creating dummy variables...
My expectation is to have an x-axis with country groups, and ordered descending by G1 (doesn't matter how G2 looks).
CodePudding user response:
You could create a separate dataframe with the right order of your G1 group and use that order to make your country a factor
based on that order. Make sure to group
on your country variable like this:
library(dplyr)
G1_order <- df %>%
filter(Variable == "G1") %>%
arrange(desc(Value)) %>%
mutate(country = factor(country))
library(ggplot2)
df %>%
mutate(country = factor(country, levels = G1_order$country, ordered = TRUE)) %>%
ggplot(aes(x = country, y = Value, fill=Variable), group = country)
geom_bar(position="dodge", stat="identity")
Created on 2022-12-14 with reprex v2.0.2
As you can see it is order based on G1.