簡體   English   中英

如何將圖例放入帶有 ggplot2 的 Plot 中?

[英]How to put legends inside a Plot with ggplot2?

我有下一個 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")

在此處輸入圖像描述

如何使用相應的顏色代碼放置圖例,如下所示: 在此處輸入圖像描述

示例中沒有數據可以完全幫助這個精確的 plot,但對於圖例定位。 這個頁面很有幫助。 您需要添加的是:

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

如鏈接帖子中所述。 legend.position 可以采用 x,y 坐標的向量。 用你需要的替換 0.8 和 0.2。

彩色線條可以 go 到一個 geom_line 調用中,您可以使用 aes(color = your_grouping_variable_here) 指定顏色。 這也會自動生成圖例。 最后,在 scale_color_manual 中添加自定義 colors:

  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))

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM