Is there really no simple way to add a legend when using ggplot() to plot multiple lines? I understand that the "right" tidyverse method is to pretend the two lines are the same variable and then add a category...i.e. switch to long format.
library(magrittr)
library(tidyverse)
library(ggplot2)
set.seed(0)
n <- 10
v1 <- rnorm(n)
v2 <- v1 + rnorm(n)
theData <- tibble(v1=v1, v2 = v2)
theData %>% ggplot(aes(x=v1)) +
geom_line(aes(y=v2),color="red") +
geom_point(aes(y=v2),color="blue")
# Would be nice to get a legend showing red line and blue points
# even if it's a silly example
Created on 2022-05-02 by the reprex package (v2.0.1)
theData %>% ggplot(aes(x=v1)) +
geom_line(aes(y=v2,color="a")) +
geom_point(aes(y=v2,color="b")) +
scale_color_manual(values = c("a"="red","b"="blue"))
1 Like
Thanks @nirgrahamuk . That is exactly what I needed. I had done a bunch of searching around and you are the only one to give such a great answer.
In case it helps anyone else, I did a little looking around and you can augment @nirgrahamuk 's answer to change the legend title by adding
+ guides(color=guide_legend("my title"))
system
Closed
May 10, 2022, 3:01pm
4
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.