简体   繁体   中英

How to put legends inside a Plot with ggplot2?

I have the next plot

ggplot(data=Predict_Fav, aes(x=Fecha, y=TotalCases)) +
  ggtitle("Posibles Escenarios de Casos Infectados de COVID-19 en Reino Unido,              
Según Tasa de Crecimiento del 31 de Marzo al 6 de Abril del 2020")+
  geom_line(aes(y=TotalCases),linetype = "twodash",color="orange")+
  geom_point(color="black")+
  geom_line(data=Data_UK7,linetype = "twodash",color="black")+
  geom_point(data= Data_UK7,  color="black")+
  geom_line(data=Predict,linetype = "twodash",color="blue")+
  geom_point(data= Predict,  color="black")+
  geom_line(data=Predict_Desfav,linetype = "twodash",color="red")+
  geom_point(data= Predict_Desfav,  color="black")+
  scale_x_date(date_breaks ="2 day")+
  xlab("Fecha")+
  ylab("Casos Confirmados Totales")

在此处输入图像描述

How I can put a legend with the corresponding color code, like this: 在此处输入图像描述

There is no data in the example to completely help with this exact plot, but for the legend positioning. This page is helpful. What you need to is add:

+ theme(legend.position = c(0.8, 0.2))

As described in linked post. legend.position can take a vector of x, y coordinates. Replace 0.8 and 0.2 with what you need.

The colored lines can go into one geom_line call and you specify the color with aes(color = your_grouping_variable_here). This will also automatically make the legend. Lastly, add custom colors in scale_color_manual:

  library(tidyverse)
  data <- tibble(x = rep(1:10,2),
           y = c(1:10, 2:11),
           group = c(rep("one", 10), rep("two", 10)))

  ggplot(data = data, aes(x = x, y = y))+
  geom_line(aes(color = group))+
  scale_color_manual(values = c("red", "blue"))+
  theme_classic()+
  theme(legend.position = c(0.2, .8))

在此处输入图像描述

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