You are better off creating a single dataset tailored to your plot needs before, which would be in the long format, so that you can give a single geom_line()
instruction, and add colors to the lines with aes(color = ...)
within the call to geom_line()
. Here's an example with the midwest
dataset (consider them as distinct datasets for the sake of example)
library(ggplot2)
library(dplyr)
library(tidyr)
long_midwest <- midwest %>%
select(popwhite, popasian, PID, poptotal) %>%
gather(key = "variable", value = "value", -PID, -poptotal) # convert to long format
long_midwest2 <- midwest %>%
select(poptotal, perchsd, PID) %>%
gather(key = "variable", value = "value", -PID, -poptotal)
plot_data <- bind_rows(long_midwest, long_midwest2) %>% # bind datasets vertically
mutate(line_type = ifelse(variable == 'perchsd', 'A', 'B')) # creates a line_type variable
ggplot(data = plot_data, aes(x=poptotal, y = value))+
geom_line(aes(color = variable, linetype = line_type)) +
scale_color_manual(
values = c('lightskyblue', 'gold1', 'blue'),
name = "My color legend"
) +
scale_linetype_manual(
values = c(3, 1), # play with the numbers to get the correct styling
name = "My linetype legend"
)

I added a line_type
variable to show the most generic case where you want specific mapping between the column values and the line type. If it is the same than, say, variable
, just use aes(color = variable, linetype = variable)
. You can then decide which linetype you want (see here for more details).
For customising the labels, just change the content of variable
within the dataset with the desired values.