Search code examples
rplotggplot2density-plot

Creating a density plot in R


I am new in R and I am trying to create a density plot. I am looking to create a plot based on some regression analysis I have done earlier. So, basically, I want to see the relationship of Z to a,b and c variables that I have. All variables have values that range between 0 and 1 (numeric).

I have been trying to use ggplot to do the plot using the following code:

     dataset$test <- data.frame(a, b, c)
     ggplot(dataset, aes(Z, colour = test)) + geom_density()

I am not sure how I can group the a,b,c variables into 1 so I can use that in the colour of the ggplot function (see test variable)

When I run the ggplot I get this error: Aesthetics must be either length 1 or the same as the data (417): x, colour.

Can anyone help me develop this plot?

Thanks!

See the sample image of what I'm going for


Solution

  • # example dataset
    df = data.frame(a = rnorm(50, 5, 6),
                    b = rnorm(50, 0, 1),
                    c = runif(50,0,1))
    
    library(dplyr)
    library(tidyr)
    library(ggplot2)
    
    df %>%
      gather(var, Z) %>%                                  # reshape dataset
      ggplot(aes(Z, fill=var))+geom_density(alpha = 0.3)  # plot data