Hot to split geom_col by different groups?

Viewed 342

I am trying to split the graph below by countries. It shows the share of education comparing 2000 with 2020. But i would like to see this comparison by countries, first germany 2000 compared with germany 2020 next to each other, then the same for the United Kingdom next to them. My guess is that i have to do it with position = "dodge", but i am not sure where to include it.

Here is my code:

ggplot(df, aes(y=share, x=country,fill= education)) + 
  geom_col(aes(time))

enter image description here

Here is the data:

  df=  structure(list(country = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
    2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Germany", "United Kingdom"
    ), class = "factor"), education = structure(c(1L, 1L, 2L, 2L, 
    3L, 3L, 1L, 1L, 2L, 2L, 3L, 3L), .Label = c("High", "Mid", "Low"
    ), class = "factor"), time = structure(c(1L, 2L, 1L, 2L, 1L, 
    2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("2000", "2020"), class = "factor"), 
        share = c(33.2845576041362, 56.9310311189152, 46.4851806022038, 
        41.3352189028342, 49.8323036187114, 38.9338040600176, 39.9891518069022, 
        48.1659773543969, 47.2698138789597, 38.9375077036854, 44.5437053326003, 
        43.9618838189481)), row.names = c(NA, -12L), class = c("tbl_df", 
    "tbl", "data.frame"))
3 Answers

We need position outside the aes in geom_col. By default, the value is "stack"

library(ggplot2)
ggplot(df, aes(y=share, x=country,fill= education)) + 
   geom_col(position = "dodge") + 
   facet_wrap(~ time)
df %>% 
  ggplot(aes(x = time, fill = education, y = share)) +
  geom_col() +
  facet_wrap(~country)

enter image description here

you may need to use facet_wrap():

library(ggplot2)
ggplot(df, aes(y=share, x=country,fill= education)) + 
    geom_col(aes(time), position = "dodge") +
 facet_wrap(~country)

the untidy way is to map country to colour aesthetic (it's not):

library(ggplot2)
ggplot(df, aes(y=share, fill= education, colour = country)) + 
    geom_col(aes(time), position = "dodge")
Related