【问题标题】:Creating density plots from two different data-frames using ggplot2使用 ggplot2 从两个不同的数据帧创建密度图
【发布时间】:2014-05-01 06:39:57
【问题描述】:

我的目标是比较各种社会经济因素(如收入)多年来的分布情况,以了解特定地区的人口在 5 年内的演变情况。这方面的主要数据来自Public Use Microdata Sample。我使用R + ggplot2 作为我的首选工具。

在比较两年的数据(2005 年和 2010 年)时,我有两个数据框 hh2005 和 hh2010 与两年的家庭数据。两年的收入数据存储在两个数据框中的变量hincp 中。使用ggplot2,我将按如下方式创建各个年份的密度图(2010 年的示例):

    p1 <- ggplot(data = hh2010, aes(x=hincp))+
      geom_density()+
      labs(title = "Distribution of income for 2010")+
      labs(y="Density")+
      labs(x="Household Income")
    p1 

如何在该图上叠加 2005 年的密度?我无法弄清楚是否已将data 读为hh2010 我不知道如何继续。我应该从一开始就以完全不同的方式处理数据吗?

【问题讨论】:

    标签: r plot ggplot2 density-plot


    【解决方案1】:

    这就是我解决问题的方法:

    1. 用感兴趣的变量(在本例中为年份)标记每个数据框
    2. 合并两个数据集
    3. 更新 ggplot 函数中的“填充”美学

    例如:

    # tag each data frame with the year^
    hh2005$year <- as.factor(2005)
    hh2010$year <- as.factor(2010)
    
    # merge the two data sets
    d <- rbind(hh2005, hh2010)
    d$year <- as.factor(d$year)
    
    # update the aesthetic
    p1 <- ggplot(data = d, aes(x=hincp, fill=year)) +
      geom_density(alpha=.5) +
      labs(title = "Distribution of income for 2005 and 2010") +
      labs(y="Density") +
      labs(x="Household Income")
    p1
    

    ^ 请注意,当您使用因子时,“填充”参数似乎效果最佳,因此我将年份定义为这样。我还使用 'alpha' 参数设置了重叠密度图的透明度。

    【讨论】:

      【解决方案2】:

      您可以将 data 参数传递给单个几何图形,因此您应该能够像这样将第二个密度添加为新几何图形:

      p1 <- ggplot(data = hh2010, aes(x=hincp))+
        geom_density() +
        # Change the fill colour to differentiate it
        geom_density(data=hh2005, fill="purple") +
        labs(title = "Distribution of income for 2010")+
        labs(y="Density")+
        labs(x="Household Income")
      

      【讨论】:

        猜你喜欢
        • 2011-11-22
        • 2021-10-17
        • 1970-01-01
        • 2021-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-27
        • 1970-01-01
        相关资源
        最近更新 更多