Search code examples
rgeom-bargeom-col

How to use geom_bar() to create two grouped columns in R


There has got to be an easy way to create one set of grouped bars for aware column and a another set of grouped bars for serious column with the individual bars within each group being the value for the respective regions. Final image should look similar to attached image. Thanks!

data I'm working with

Image I'm seeking approximately

by_region <- country_obs_df %>%
  group_by(Region) %>%
  summarize(
    #region_avg_gdp = GDPperUS,
    #region_avg_co2 = CO2emi,
    #region_avg_pop = Population.2008,
    region_avg_aware = mean(Aware),
    region_avg_serious = mean(Serious)
  )
ggplot(by_region) +
  geom_col(mapping = aes(fill = Region, x = Region, y=region_avg_aware), position = "dodge") +
  labs(y = "Percent")

Solution

  • An option is to pivot to 'long' format then, use geom_col

    library(dplyr)
    library(ggplot2)
    library(tidyr)
    by_region %>%
        pivot_longer(cols = -Region, names_to = 'region_avg') %>%
        ggplot(aes(x = region_avg, y = value, fill = Region)) +
             geom_col( position = "dodge") +
             labs(y = "Percent")
    

    -output

    enter image description here

    data

    by_region <- structure(list(Region = c("Africa", "Asia", "Europe", "Europe (North America)", 
    "Europe (Oceania)", "Latin America & Caribbean"), region_avg_aware = c(39.9, 
    60.9, 88.3, 96.6, 97.3, 63.8), region_avg_serious = c(82.3, 76.3, 
    67.7, 71.1, 78.2, 93.8)), class = "data.frame", row.names = c(NA, 
    -6L))