有没有办法向包含密度函数的多线图添加图例?

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

我想为多条线图添加图例,每条线都是用 geom_density 函数创建的。我找不到任何解决方法。

# 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

您遇到的问题是因为您使用的是 wide table,而不是 long一。宽 table 很适合在电子表格中输入值,但对于您打算进行的严肃分析来说并不是最好的。

所以,第一件事就是将宽数据转换为长格式。由于你没有提供任何数据,我会做一些假人:

# 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()

从那时起,您可以开始对轴、标签等进行修饰

它产生: