1
votes

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

1
It always helps to include the dataset in the question, or if it is too big, generate some sample. Can you run 'dput(dataset)` and add the output to your question? - Michael Harper
However my guess is that you are doing some wrong in the first line when creating dataset$test - Michael Harper
Hi Mikey, thanks for answering. I'm afraid the dput output is also too big. Is there something specific you need to know so I can tell you? But yes, I have a strong feeling that my test variable is not as it should be. So the issue I guess is to group the 3 variables into 1? - Chris M.
Are you sure that density is what you're looking for? I can see you want to see relationships between numeric variables. Density will give you the distribution of a specific variable. - AntoniosK
Hi Antoni, I have added a sample image of what I am trying to create. Please see the link above. I want to see the density of the data, so how the Z data distributes across those 3 variables in one chart. - Chris M.

1 Answers

1
votes
# 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