I have a question related to ordering specific values of a bar chart created with ggplot.
My data "df" is the following:
city X2020 X2021
1 Stuttgart 2.9 3.1
2 Munich 2.3 2.4
3 Berlin 2.2 2.3
4 Hamburg 3.8 4.0
5 Dresden 3.3 3.0
6 Dortmund 2.5 2.6
7 Paderborn 1.7 1.8
8 Essen 2.6 2.6
9 Heidelberg 3.0 3.2
10 Karlsruhe 2.5 2.4
11 Kiel 2.6 2.7
12 Ravensburg 3.3 2.7
I want exactly this kind of barchart below, but cities should be only ordered by the value of 2021! I tried "reorder" in the ggplot as recommended, but this does not fit. There are some cities where the ordering is pretty weird and I do not understand what R is doing here. My code is the following:
df_melt <- melt(df, id = "city")
ggplot(df_melt, aes(value, reorder(city, -value), fill = variable)) +
geom_bar(stat="identity", position = "dodge")
str(df_melt)
'data.frame': 24 obs. of 3 variables:
$ city : chr "Stuttgart" "Munich" "Berlin" "Hamburg" ...
$ variable: Factor w/ 2 levels "X2020","X2021": 1 1 1 1 1 1 1 1 1 1 ...
$ value : num 2.9 2.3 2.2 3.8 3.3 2.5 1.7 2.6 3 2.5 ...
https://i.stack.imgur.com/rJQMV.png
I think this gets messy because in the variable "value" there are values of both 2020 and 2021 and R possibly takes the mean of both (I dont know!). But I have no idea to deal with this further. I hope somebody can help me with my concern.
Thanks!