Change legend title and legend values in geom_line

Viewed 27

For a sample dataframe:

     df <- tibble(
      x = c(1:6, 1:6),
      y = c(1, 5, 6, 4, 1, 1, 1, 4, 5, 4, 2, 2),
      f = c(rep("a", 6), rep("b", 6)) 
    )

I am plotting line graphs of 'f' with their corresponding x and y coordinates.

p <- ggplot(df, aes(x,y, group = f))+
  geom_line(aes(linetype = f, col = f))
p

I am however trying to change the legend title from 'f' to "animal" and "a" to "cat" and "b" to dog. When I try to run:

p <- ggplot(df, aes(x,y, group = f))+
  geom_line(aes(linetype = f, col = f))+
  scale_linetype_manual(name = "Animal", labels = c("cat", "dog"))
p

I get the error: Error in f():

! Insufficient values in manual scale. 2 needed but only 0 provided.
Run `rlang::last_error()` to see where the error occurred.

Can someone please explain why when I am inputting two labels (cat/dog), ggplot2 doesn't recognise them as such.

1 Answers

Update:

ggplot(df, aes(x,y, group = f, color=f))+
  geom_line(linetype = 2)+
  labs(color = "Animal")+
  scale_color_manual(labels = c("cat", "dog"), values = c("blue", "red"))

enter image description here

Are you looking for such a solution:

We have to change the code a little. Rule of thumb and what helps is to remember each aes will show a legend. And if the aes is color we can change them as appropriate:

library(ggplot2)

ggplot(df, aes(x,y, group = f, color=f))+
  geom_line()+
  labs(color = "Animal")+
  scale_color_manual(labels = c("cat", "dog"), values = c("blue", "red"))

enter image description here

Related