简体   繁体   English

将手动图例添加到 ggplot2

[英]Adding manual legend to ggplot2

I plotted two lines on the same plot thanks to ggplot由于ggplot ,我在同一个plot上绘制了两条线

ggplot() + 
geom_line(data=df_density0, aes(x = x, y = y), color = "darkred") + 
geom_line(data=df_density1, aes(x = x, y = y), color="steelblue", linetype="twodash") +
xlab('') +
ylab('Density')

I would like to add manually a legend in this plot.我想在这个 plot 中手动添加一个图例。 For example, for the line with darkred color I would like to write Target = 0 , whereas for the line with steelblue color I would like to write Target = 1 .例如,对于darkred的线,我想写Target = 0 ,而对于steelblue蓝色的线,我想写Target = 1

Instead of answering the question about how to add a manual legend, I'll give an example of the typical way to add legends.我将举例说明添加图例的典型方法,而不是回答有关如何添加手动图例的问题。

I suppose you have data of the following structure:我想你有以下结构的数据:

library(ggplot2)

df_density0 <- density(rnorm(100))
df_density0 <- data.frame(
  x = df_density0$x,
  y = df_density0$y
)

df_density1 <- density(rnorm(100, mean = 1))
df_density1 <- data.frame(
  x = df_density1$x,
  y = df_density1$y
)

You can just set aes(colour =...) to text that you want your legend label to be.您可以将aes(colour =...)设置为您希望您的图例 label 成为的文本。 Then in the scale, you can set the actual colour that you want to use.然后在比例中,您可以设置您想要使用的实际颜色。

ggplot(mapping = aes(x = x, y = y)) +
  geom_line(data = df_density0, aes(colour = "Target = 0")) +
  geom_line(data = df_density1, aes(colour = "Target = 1")) +
  scale_colour_manual(
    values = c("darkred", "steelblue")
  )

Created on 2021-04-10 by the reprex package (v1.0.0)代表 package (v1.0.0) 于 2021 年 4 月 10 日创建

This is a variation on the theme expressed by @teunbrand - just another way to do the same thing but including the linetype option.这是@teunbrand 表达的主题的变体——只是做同样事情的另一种方式,但包括linetype选项。 The focus is on getting the data into 'tidy' or 'long' format.重点是将数据转换为“整齐”或“长”格式。

library(ggplot2)
library(dplyr)

df_density0 <- 
  data.frame(x = c(1, 3),
             y = c(4, 5)) %>% 
  mutate(df = "dens0")

df_density1 <- 
  data.frame(x = c(1, 3),
             y = c(1, 1.5)) %>%
  mutate(df = "dens1")

df <- bind_rows(df_density0, df_density1)
  

ggplot(df) + 
  geom_line(aes(x = x, y = y, colour = df, linetype = df)) +
  scale_colour_manual(values = c("dens0" = "darkred", "dens1" = "steelblue"))+
  scale_linetype_manual(values = c("dens0" = "solid", "dens1" = "twodash"))+
  xlab('') +
  ylab('Density')

Created on 2021-04-10 by the reprex package (v2.0.0)代表 package (v2.0.0) 于 2021 年 4 月 10 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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