Legend in ggplot2

hejseb

I am trying to understand how to change the title and labels in the legend when using ggplot2 in R. I have searched online trying to find the answer, and it seems like I need to use the scale_xxx_yyy command in some way, but I can't seem to get it right. A simple example:

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"))

I want the legend to have title "Kernels" and labels "Rectangular" and "Gaussian", but nothing happens. I have also tried scale_linetype_discrete(name = "Kernels") and labs(linetype="Kernels") as suggested elsewhere, buit still nothing.

What am I doing wrong?

jazzurro

Try this. As @Pascal said, scale_color_discrete is the one for you. I guess the more you us ggplot2, the more you get used to the scale_xxx_yyy business. The cookbook suggested by @A.Val is a great book. Here is the link for you

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"))

enter image description here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related