2

必须有一种简单的方法来创建一组用于感知列的分组条和另一组用于严重列的分组条,每个组中的各个条是各个区域的值。最终图像应与附加图像相似。谢谢!

我正在使用的数据

我正在寻找的图像大约

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

2 回答 2

1

当然,有可能,您必须将数据重新格式化为 long,以便您拥有行格式所需的变量以便进行绘图。这里使用您共享的数据屏幕截图的代码:

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

输出:

在此处输入图像描述

于 2020-09-30T22:03:06.640 回答
1

一个选项是转为“长”格式,然后使用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")

-输出

在此处输入图像描述

数据

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))
于 2020-09-30T22:03:07.590 回答