Search code examples
rggplot2legendkernel-density

Is there a way to add a legend to a multiple line graph including the density function?


I want to add a legend to a line diagramm with multiple lines, every line was created with a geom_density function. I can't find any solution how to do so.

# This is my code:

ggplot(Flugzeiten, aes(x = Falconidae)) + 
  scale_x_continuous (breaks=c(0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220)) +
  geom_density(kernel="gaussian", size=1.2, color = "blue") +
  geom_density(aes(x = Milvus), kernel="gaussian", color = "red", size=1.2) + 
  geom_density(aes(x = Buteo), kernel="gaussian", color = "green", size=1.2) +
  geom_density(aes(x = Gesamt), kernel="gaussian", color = "black", size=1, linetype ="dotted") +
  theme(axis.text.y=element_blank()) +
  labs(x = "Fluglänge (s)", y = "Häufigkeitsverteilung", title = "Aufenthalte im Gefahrenbereich nach Flugzeit")```

# This is my Data:


# A tibble: 39 x 4
   Falconidae Buteo Milvus Gesamt
        <dbl> <dbl>  <dbl>  <dbl>
 1         59    63    117    117
 2        112   197     97     97
 3          1    75    156    156
 4         32    67    142    142
 5         68   115     52     52
 6         22   115     41     41
 7         28    26    155    155
 8         NA    74    159    159
 9         NA     4    111    111
10         NA    73     84     84


Solution

  • The problem you're having is because you're working with a wide table, instead of a long one. Wide tables are nice to input values in a spreadsheet, but aren't the best for the serious analysis you intend to do.

    So, the first thing is to convert your wide data to long format. Since you didn't provide any data, I'll make some dummy:

    # create dummy data
    a <- data.frame(x = sample(1:100, 10), y = sample(1:100, 10), z = sample(1:100, 10))
    
    # convert to data.table so it can be reshaped with melt:
    library(data.table)
    setDT(df)
    
    # reshape the data:
    newA <- melt(a) #ignore the warning
    
    # plot it the right way:
    library(ggplot2)
    ggplot(newA, aes(x = value, color = variable))+geom_density()
    

    From there on, you can start doing the cosmetics to axis, labels, etc.

    It produces: enter image description here