Creating density plots from two different data-frames using ggplot2

白昼怎懂夜的黑 提交于 2019-12-05 20:03:09

You can pass data arguments to individual geoms, so you should be able to add the second density as a new geom like this:

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")

This is how I would approach the problem:

  1. Tag each data frame with the variable of interest (in this case, the year)
  2. Merge the two data sets
  3. Update the 'fill' aesthetic in the ggplot function

For example:

# 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

^ Note, the 'fill' parameter seems to work best when you use a factor, thus I defined the years as such. I also set the transparency of the overlapping density plots with the 'alpha' parameter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!