简体   繁体   中英

How to add a legend on a multiple line graph in R?

I am trying to plot two different datasets on the same plot. I am using this code to add the lines and to actually plot everything

ggplot()+
geom_point(data=Acc, aes(x=Year, y=Accumulo), color="lightskyblue")+
geom_line(data=Acc, aes(x=Year, y=RM3), color="gold1")+
geom_line(data=Acc, aes(x=Year, y=RM5), color="springgreen3")+
geom_line(data=Acc, aes(x=Year, y=RM50), color="blue")+
geom_line(data=Vulcani, aes(x=Year, y=Accumulo.V), color="red")+
theme_bw()+
scale_x_continuous(expand=expand_scale(0)) + scale_y_continuous(limits=c(50,350),expand=expand_scale(0))

but I can't find any way to add a legend and add custom labels to the different series. I find a way to add legends on a single dataset, but I can't find a way to add to this one a legend on the side

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM