将图例添加到由两列组成的 ggplot

Adding legend to a ggplot made from two columns

我正在使用以下代码绘制两种不同方法的残差:

ggplot(df_index, aes(cases100ppl, lm_errors)) +
  geom_point(alpha=1) +
  geom_point(data=df_index, aes(cases100ppl, error), col="red", alpha=0.2) 

如何添加图例?

数据的结构如下:

code       cases100ppl   error         lm_errors
E02000001  0.05575558    0.2228769     0.1554760                
E02000002  0.11299289    0.3680860     0.4357544            
E02000003  0.11938429    0.4785204     0.3163543            
E02000004  0.10767160    0.1978992     0.3909933            
E02000005  0.11138804    0.3544542     0.3370886            
E02000007  0.09484474    0.3447380     0.3881657

输出看起来像这样: 谢谢!

您需要稍微更改一下数据,以便可以使用 aes() 设置颜色和 alpha。这是 ggplot 的一个非常有用的技巧(您可以在 this one). You can find more general informations about pivoting here in the book R for data science, chapter 12 Tidy data.

等 SO 帖子上找到实现它的方法,包括此处介绍的方法

因此,我旋转你的数据框以创建一个名为 error_type 的新变量。然后在 aes() 中使用这个新变量,因此相应地创建了图例。请注意,使用 dplyr 管道符号 %>% 我在进入 ggplot 世界之前旋转你的数据框,而不更改原始 df_index 对象。

然后您可以使用scale_alpha_manual()scale_colour_manual() 以您想要的方式自定义颜色和 alpha。

这是一个开始:

library(dplyr)
library(tidyr)
library(ggplot2)

df_index %>% 
  pivot_longer(cols = c("error", "lm_errors"), names_to = "error_type", values_to = "error_value") %>% 
  ggplot(data = ., aes(x = cases100ppl, 
                       y = error_value, 
                       color = error_type, 
                       alpha = error_type)) + # do not forget to put alpha inside aes()!
  scale_alpha_manual(values = c("error" = 0.3, "lm_errors" = 1)) +
  geom_point()

数据:

df_index <- structure(list(code = c("E02000001", "E02000002", "E02000003", 
                                    "E02000004", "E02000005", "E02000007"), cases100ppl = c(0.05575558, 
                                                                                            0.11299289, 0.11938429, 0.1076716, 0.11138804, 0.09484474), error = c(0.2228769, 
                                                                                                                                                                  0.368086, 0.4785204, 0.1978992, 0.3544542, 0.344738), lm_errors = c(0.155476, 
                                                                                                                                                                                                                                      0.4357544, 0.3163543, 0.3909933, 0.3370886, 0.3881657)), class = "data.frame", row.names = c(NA, 
                                                                                                                                                                                                                                                                                                                                   -6L))