【问题标题】:How do you create a plot from two different data frames (or how do you combine data frames with identical column names)如何从两个不同的数据框创建图(或如何将具有相同列名的数据框组合起来)
【发布时间】:2020-08-19 02:47:32
【问题描述】:

我有两个数据框,我想对它们进行比较。情节和数据框看起来像这样

df2019 <- data.frame(Institute = c("A","B","C"),Women = c(65,50,70),Men = c(35,50,30))
df2016 <- data.frame(Institute = c("A","B","C"),Women = c(70,45,50),Men = c(30,55,50))

df2019_melted <- melt(df2019)

ggplot(data = df2019_melted, aes(x = Institute, y = value, fill = variable))+
  geom_bar(stat = "identity", position = "dodge")+
  labs(fill = "Gender")+
  xlab("Institute")+
  ylab("Percent")+
  scale_fill_discrete(labels = c("Women","Men"))+
  ggtitle("Overall Gender Composition 2019")

但我希望情节以褪色条形显示 2016 年,但分组方式与 2019 年相同,因此每个研究所 4 个条形。

由于我的所有数据帧的列名都相同,因此我不能使用 rbind() 或类似方法,因为它无法区分组合时的数据帧。

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

    将年份列添加到您的数据框中,然后合并并融合。 ggplot 更喜欢所有东西都在一个 data.frame 中

    all_melted <- reshape2::melt(
      rbind(cbind(df2019, year=2019), cbind(df2016, year=2016)),
      id=c("year", "Institute"))
    

    然后你可以用这样的东西来绘制,将年份映射到 alpha 以制作“褪色”条

    ggplot(all_melted, aes(x = Institute, y = value, fill = variable, alpha=factor(year)))+
      geom_col(position = "dodge")+
      labs(fill = "Gender")+
      xlab("Institute")+
      ylab("Percent")+
      scale_alpha_discrete(range=c(.4, 1), name="Year") + 
      ggtitle("Overall Gender Composition")
    

    【讨论】:

      猜你喜欢
      • 2021-07-28
      • 1970-01-01
      • 2021-01-16
      • 2021-03-20
      • 2021-03-20
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      相关资源
      最近更新 更多