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

人盡茶涼 提交于 2021-01-28 02:13:24

问题


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")

回答1:


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

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))



回答2:


For sure, it is possible, you have to reformat your data to long so that you have the required variables in a row format in order to be plotted. Here the code using the data screenshot you shared:

library(tidyverse)
#Data
df <- data.frame(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))
#Plot
df %>% pivot_longer(-Region) %>%
  ggplot(aes(x=name,y=value,group=Region,fill=Region))+
  geom_bar(stat = 'identity',position = position_dodge(0.9))+
  theme_bw()+
  theme(axis.text = element_text(color='black',face='bold'),
        axis.title = element_text(color='black',face='bold'),
        legend.text = element_text(color='black',face='bold'),
        legend.title = element_text(color='black',face='bold'),
        panel.grid = element_blank())+
  xlab('Variable')

Output:



来源:https://stackoverflow.com/questions/64146274/how-to-use-geom-bar-to-create-two-grouped-columns-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!