You will need to change a little your data so you can use aes()
to set the color and the alpha. This is a very usefull trick with ggplot (you can find ways to do it, including the one presented here, on SO posts like this one). You can find more general informations about pivoting here in the book R for data science, chapter 12 Tidy data.
Accordingly, I pivot your dataframe to make a new variable called error_type
. This new variable is then used inside aes()
so the legend is created accordingly. Note that, using, dplyr
pipe symbol %>%
I pivot your dataframe just before entering ggplot world, without changing the original df_index
object.
Then you can usescale_alpha_manual()
and scale_colour_manual()
to custom the color and the alpha the way you want it to be.
Here is a start:
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()

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