简体   繁体   中英

Distributions over time (plotting multiple distributions on the same graph in R)

I have datasets similar to the one represented below (though much longer) for different years. They are separate dataframes and have different number of observations, so I did not merge then. I would like to make a graph that allows me to compare the evolution of the distribution of tenure over time. So I would like to make a graph with 4 density plots for 4 reference years. How can I achieve that in R?

tenure
2
3
1
4
0.5
3
7
8
9
3
1
2.5
6
4
4.5
5

Here is one way to do it. You can marge the dataframes by row if they have the same column types and names. Then you can easily create a plot using ggplot2

library(ggplot2)

set.seed(123)

d1 <- data.frame(year = "2010", x = rnorm(100, mean = 0.5))
d2 <- data.frame(year = "2011", x = rnorm(100, mean = 0.7))
d3 <- data.frame(year = "2012", x = rnorm(100, mean = 1.5))
d4 <- data.frame(year = "2013", x = rnorm(100, mean = 1.2))

rbind(d1,d2,d3,d4) |>
  ggplot() +
  geom_density(aes(x = x, color = year))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM