【问题标题】:How to create a geom_bar of two tables using ggplot如何使用 ggplot 创建两个表的 geom_bar
【发布时间】:2017-12-26 15:02:00
【问题描述】:

我在使用 ggplot 创建 geom_bar 两个表时遇到问题。 我有两张桌子:

1) 
  characteristic men_weekly_earnings
1     16 to 24 years               493
2     16 to 19 years               392
3     20 to 24 years               507
4     25 to 34 years               755
5     35 to 44 years               964
6     45 to 54 years              1011
7     55 to 64 years              1021
8 65 years and older               942


2)
  characteristic women_weekly_earnings
1     16 to 24 years                 451
2     16 to 19 years                 357
3     20 to 24 years                 468
4     25 to 34 years                 679
5     35 to 44 years                 781
6     45 to 54 years                 780
7     55 to 64 years                 780
8 65 years and older                 740

每个表格都有不同年龄的每周收入数据。 我的目标是将两张表合二为一 like this.

x 轴是特征列,y 轴是每周收入列。

现在我尝试了这段代码(对于 men 表,它不起作用

  ggplot(data = men) + geom_col(mapping = aes(x= characteristic,y=  men_weekly_erning))

我现在能做什么?

谢谢。

【问题讨论】:

  • 您遇到的错误是什么?

标签: r dataframe ggplot2 geom-bar


【解决方案1】:

欢迎来到 Stack Overflow!

我认为您最好的选择是将两个数据集堆叠在一起然后绘制它们。像这样的:

df_all <- rbind(cbind(setNames(men_df, c("characteristic", "weekly_earnings")), source = "men"),
                cbind(setNames(women_df, c("characteristic", "weekly_earnings")), source = "women"))


ggplot(data = df_all) + 
   geom_col(mapping = aes(x= source, y =  weekly_earnings, fill = characteristic), position = position_dodge())

请注意,当我创建 df_all 时,我将添加一个列,根据数据的来源来指定来源(“男人”/“女人”)。这使您可以在 ggplot 调用中将其分解。另请注意,在堆叠之前,我必须使两个数据集之间的列名一致。我为此使用了setNames 命令。


数据:

women_df <- structure(list(characteristic = c("16 to 24 years", "16 to 19 years", 
"20 to 24 years", "25 to 34 years", "35 to 44 years", "45 to 54 years", 
"55 to 64 years", "65 years and older"), women_weekly_earnings = c(451L, 
357L, 468L, 679L, 781L, 780L, 780L, 740L)), .Names = c("characteristic", 
"women_weekly_earnings"), row.names = c(NA, -8L), class = "data.frame")

men_df <- structure(list(characteristic = c("16 to 24 years", "16 to 19 years", 
"20 to 24 years", "25 to 34 years", "35 to 44 years", "45 to 54 years", 
"55 to 64 years", "65 years and older"), men_weekly_earnings = c(493L, 
392L, 507L, 755L, 964L, 1011L, 1021L, 942L)), .Names = c("characteristic", 
"men_weekly_earnings"), row.names = c(NA, -8L), class = "data.frame")

【讨论】:

    猜你喜欢
    • 2019-02-13
    • 2020-05-23
    • 2021-01-05
    • 2011-04-29
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 2011-12-29
    相关资源
    最近更新 更多