No legend in ggplot

Hi, why does the following not create the legend I am expecting with the last line?

library(dplyr)
library(ggplot2)
df <- data.frame(x=c(1,2,3,4,5), y=c(2,4,6,8,10), z=c(3,6,9,12,15))
df %>%
ggplot() +
geom_line(aes(x = x, y = y), color="blue") +
geom_line(aes(x = x, y = z), color="red") +
scale_color_manual(values=c("blue", "red"), labels=c("Alabama sales of blue widgets",
"Arizona sales of red widgets"))

In ggplot world legends are generated for aes() things, and your color is fixed and not an aes member.

1 Like

For get the legend you need plot each line and put the name of each legend in color.

Each call to geom_line() has an aes argument that specifies how the data frame variables are mapped to the aesthetic elements of the graph. The color argument is used to assign colors to each line.

df <- data.frame(x=c(1,2,3,4,5), y=c(2,4,6,8,10), z=c(3,6,9,12,15))
df %>%
  ggplot() +
  geom_line(aes(x = x, y = y, color = "Alabama sales of blue widgets")) +
  geom_line(aes(x = x, y = z, color = "Arizona sales of red widgets")) +
  scale_color_manual(values=c("blue", "red")) +
  labs(color = "") 

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.