简体   繁体   中英

Ordering a variable by a specific year in ggplot bar chart R

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!

You could try sorting your df with arrange and then use fct_inorder to ensure that the city levels is in the order that you want.

library(tidyverse)

df <- read_table("         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 ")
#> Warning: Missing column names filled in: 'X1' [1]


df %>% 
  select(-X1) %>% 
  pivot_longer(-city) %>% 
  arrange(desc(name), -value) %>% 
  mutate(
    city = fct_inorder(city)
  ) %>% 
  ggplot(aes(city, value, fill = name)) +
  geom_col(position = "dodge")

Created on 2021-07-13 by the reprex package (v1.0.0)

I just want to add to the previous answer that you can also take this plot and use coord_flip() to achieve the final result you were looking for. 😉

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM