Search code examples
rdensity-plot

Density plot between multiple categories in R


I have a text file of a data set. It lists two variables: the individual it comes from and a particular value associated with that individual. For convenience, let's say it's a person and arbitrary weight measurements through their life.

The file is set up as follows (with headers):

person     weight #header line
individual_1     arbitrary_weight_value
individual_2     arbitrary_weight_value
individual_3     arbitrary_weight_value
individual_1     arbitrary_weight_value

And so on. I am trying to use R to create a density plot of each individuals weights. The total density plot of all weights is done as follows:

d <- density(my_data$weight)
plot(d)

However, I want an individual density plot for each person. How would I do that?


Solution

  • Is this dataframe similar to the actual data you have?

    df <- data.frame(id = rep(LETTERS[1:8], 10), weight = as.integer(rnorm(80, 80, 10)))
    
    > head(df)
      id weight
    1  A     78
    2  B     72
    3  C     76
    4  D     58
    5  E     84
    6  F     78
    
    library(ggplot2)
    ggplot(df, aes(x=weight)) + 
      geom_density(alpha=.2, fill="#FF6666") +
      facet_wrap( ~ id, nrow=2)
    

    enter image description here