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
CodePudding user response:
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))