繁体   English   中英

在 R 中使用 geom_bar 绘制几个变量

[英]Plot several variables using geom_bar in R

我想用几个变量绘制条形图,并根据它们的和上升值排列它们。 为了重现这个问题,我将使用以下示例:

df <- data.frame(
  stringsAsFactors = FALSE,
         Country = c("France","Germany","Spain",
                       "Mexico","Colombia","Brasil","China","Vietnam",
                       "Japan"),
                 a = c(272, 172, 301, 245, 270, 284, 281, 294, 225),
                 b = c(640, 398, 689, 603, 619, 654, 616, 632, 430),
                 c = c(1007, 623, 1078, 961, 968, 1024, 951, 971, 635),
                 d = c(1375,849,1467,1318,
                       1317,1394,1285,1310,839),
             Group = c("Group 1","Group 1","Group 1",
                       "Group 2","Group 2","Group 2","Group 3","Group 3",
                       "Group 3"))

#First I arrange my data in the desire order

library(dplyr)
df2 <- df %>% 
  arrange(Group, d) %>%
  mutate(Country = factor(Country, levels = Country),
         Group =factor(Group))

#I created a plot that will be used as a "base"

library(ggplot2)
ggplot(df2, aes(x = Country, y = d , fill = Group))+
  geom_bar(stat="identity",  col = "black")+
  scale_fill_manual(values = c ("blue", "orange", "pink"))+
  ylab("Country")+
  xlab("Values")+
  theme_classic()+
  theme(axis.text.x = element_text(angle = 90, vjust =0.2, hjust = 1))

#that resulted in: 

底图

#现在问题来了。 我想使用 geom_bar 添加其余的变量(a、b 和 c),因为我想为每一列添加不同的纹理,所以我这样编码:

ggplot(df2, aes(x = Country, y = d , fill = Group))+
  geom_bar(position = "dodge", stat="identity",  col = df$Group)+
  geom_bar(df2, aes(x = Country, y = a, fill='blank'))+
  geom_bar(df2, aes(x = Country, y = b, fill= 'hdashes'))+
  geom_bar(df2, aes(x = Country, y = c, fill= 'crosshatch'))+
  scale_fill_manual(values = c ("00028", "gray", "olivedrab1"))+
  ylab("Country")+
  xlab("Values")+
  theme_classic()+
  theme(axis.text.x = element_text(angle = 90, vjust =0.2, hjust = 1))

R 不接受此代码。

以下是我想要的情节:

想要的情节

任何帮助,将不胜感激。

您应该首先将表格转换为整洁的数据。

library(tidyr)
df3 <- pivot_longer(df2, cols = 2:5, names_to = "variable", values_to = "value")

从您提供的数据框中,您将获得一个包含 36 个观测值和 4 个变量的新数据框。 然后在 ggplot 中使用geom_col代替。 我无法为列添加纹理,但作为替代,您可以通过添加美观的“alpha”来更改列的透明度。

df3 %>% ggplot(aes(x=Country, y = value)) +
  geom_col(mapping=aes(x=Country, fill= Group, alpha=variable), position = "dodge2")+
  scale_fill_manual(values = c ("blue", "orange", "pink"))+
  scale_alpha_manual(values = c(0.2,0.4,0.6,0.8))+
  ylab("Values")+
  xlab("Country")+
  theme_classic()+
  theme(axis.text.x = element_text(angle = 90, vjust =0.2, hjust = 1))

如果您真的想添加纹理,您可以在此处查看@Docconcoct 对类似问题的回答: https ://stackoverflow.com/a/20426482/16281137

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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