sri*_*amn 3 plot r ggplot2 density-plot
我的目标是比较各种社会经济因素(如多年收入)的分布情况,以了解人口在特定地区的演变情况,例如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
Run Code Online (Sandbox Code Playgroud)
如何在此图上叠加2005年的密度?我无法弄清楚data因为hh2010我不知道如何继续阅读.我应该从一开始就以一种根本不同的方式处理数据吗?
Mar*_*ius 10
您可以将data参数传递给各个geoms,因此您应该能够将第二个密度添加为新的geom,如下所示:
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")
Run Code Online (Sandbox Code Playgroud)