【问题标题】:Is there a way to add a legend to a multiple line graph including the density function? [duplicate]有没有办法将图例添加到包括密度函数的多线图? [复制]
【发布时间】:2019-10-29 03:33:27
【问题描述】:

我想在具有多条线的线图中添加一个图例,每条线都是使用 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

【问题讨论】:

    标签: r ggplot2 legend kernel-density


    【解决方案1】:

    您遇到的问题是因为您使用的是表,而不是表。宽表很适合在电子表格中输入值,但不适合您打算进行的认真分析。

    因此,首先要将宽数据转换为长格式。既然你没有提供任何数据,我就做一些假的:

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

    从那里开始,你可以开始为轴、标签等做化妆品了。

    它产生:

    【讨论】:

    • 天才,绝对的天才,非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    • 2021-11-18
    • 1970-01-01
    相关资源
    最近更新 更多