Nuramon
Nuramon

Reputation: 79

How do I plot multiple density curves and add a legend?

dear swarm intelligence.

I am facing an issue trying to plot different density curves in one ggplot object and having it also display a legend.
I have tried two approaches so far:

multiple_density <- ggplot() + 
  geom_density(data = df1, mapping = aes(x = df1$col1), color = "black") + 
  geom_density(data = df2, mapping = aes(x = df2$col1), color = "red") +
  geom_density(data = df3, mapping = aes(x = df3$col1), color = "green") +
  theme(legend.position = "right") +
  scale_colour_manual(values = c("black" = "black", "red" = "red", "green" = "green"), name = "key") +
  theme_classic()

And:

combined_df <- bind_rows(df1, df2, df3, .id = "id")

multiple_density <- ggplot() +
  geom_density(data = multiple_density, mapping = aes(x = combined_df$col1) + 
  theme(legend.position = "right") + 
  theme_classic()

In the first code, I would expect the scale_colour_manual bit to do the trick, which is what I have found in answers to such questions before, this does however not work for me.
Could the problem here be, that the different data frames do not have the same number of values in their respective col1?

The second code does not give me 3 distinct curves but takes all values from the 3 data frames together as one density curve, which I obviously don't want.

I am probably missing something obvious here, but any help would still be appreciated!

Upvotes: 0

Views: 231

Answers (1)

Limey
Limey

Reputation: 12461

To expand on my comment above, and based on random data:

library(tidyverse)

df1 <- tibble(col1=rnorm(500, mean=0))
df2 <- tibble(col1=rnorm(500, mean=2))
df3 <- tibble(col1=rnorm(500, mean=4))

df1 %>% 
  bind_rows(df2, df3, .id="DF") %>% 
  ggplot() +
    geom_density(aes(x=col1, color=DF))

enter image description here

Upvotes: 1

Related Questions