ggplot2 中的图例

Legend in ggplot2

我想了解在 R 中使用 ggplot2 时如何更改图例中的标题和标签。我在网上搜索试图找到答案,看来我需要使用 scale_xxx_yyy以某种方式命令,但我似乎无法正确执行。一个简单的例子:

x <- rnorm(100)

dens1 <- density(x, 0.1, kernel = "rectangular")
dens2 <- density(x, 0.1, kernel = "gaussian")

df <- data.frame(x = dens1$x, y1 = dens1$y, y2 = dens2$y)

pl <- ggplot(df, aes(x)) + geom_line(aes(y=y1, colour = "y1")) + geom_line(aes(y=y2, colour = "y2"))
pl + scale_fill_discrete(name="Kernels", breaks=c("y1", "y2"), labels=c("Rectangular", "Gaussian"))

我希望图例具有标题 "Kernels" 以及标签 "Rectangular" 和 "Gaussian",但没有任何反应。我也按照其他地方的建议尝试了 scale_linetype_discrete(name = "Kernels")labs(linetype="Kernels"),但仍然一无所获。

我做错了什么?

试试这个。正如@Pascal 所说,scale_color_discrete 适合您。我猜你使用 ggplot2 的次数越多,你就越习惯 scale_xxx_yyy 业务。 @A.Val推荐的食谱是一本很棒的书。这是the link给你的

library(dplyr)
library(tidyr)
library(ggplot2)

df <- data.frame(x = dens1$x, y1 = dens1$y, y2 = dens2$y) %>%
      gather(variable, value, - x)

ggplot(df, aes(x = x, y = value, color = variable)) +
geom_line() +
scale_color_discrete(name = "Kernels", breaks=c("y1", "y2"), labels =c("Rectangular", "Gaussian"))