I have two custom functions:
plt_regression_line <- function(color = "black", linetype = "dashed"){
list(
ggplot2::geom_smooth(
method = "lm",
se = FALSE,
formula = "y ~ x",
mapping = ggplot2::aes(alpha = "Regression line"),
linetype = linetype,
color = color),
ggplot2::labs(alpha = ""),
ggplot2::scale_alpha_manual(values = c(1,1))
)
}
and
plt_identity_line <- function(color = "black", linetype = "dashed"){
list(
ggplot2::geom_abline(
mapping = ggplot2::aes(slope = 1, intercept = 0,alpha = "Identity line"),
linetype = linetype,
color = color),
ggplot2::labs(alpha = ""),
ggplot2::scale_alpha_manual(values = c(1,1))
)
}
They work perfect individually, but when I combine them the legend does not distinguish on from another:
library(ggplot2)
ggplot(mtcars,aes(qsec,mpg))+
geom_point()+
plt_regression_line(color = "red",linetype = 1)+
plt_identity_line(color = "blue",linetype = 1)
*I use alpha, since col and fill can be used for others variables and I want to show them in the legend.
>Solution :
You are using the ‘alpha’ aesthetic twice, so ggplot is combining the legends. One potential option is to use another aesthetic, e.g. linewidth, for one of the functions:
library(tidyverse)
plt_regression_line <- function(color = "black", linetype = "dashed"){
list(
ggplot2::geom_smooth(
method = "lm",
se = FALSE,
formula = "y ~ x",
mapping = ggplot2::aes(alpha = "Regression line"),
linetype = linetype,
color = color),
ggplot2::labs(alpha = ""),
ggplot2::scale_alpha_manual(values = c(1,1))
)
}
plt_identity_line <- function(color = "black", linetype = "dashed"){
list(
ggplot2::geom_abline(
mapping = ggplot2::aes(slope = 1, intercept = 0,linewidth = "Identity line"),
linetype = linetype,
color = color),
ggplot2::labs(linewidth = ""),
ggplot2::scale_linewidth_manual(values = c(0.5,0.5))
)
}
ggplot(mtcars,aes(qsec,mpg))+
geom_point()+
plt_regression_line(color = "red",linetype = 1) +
plt_identity_line(color = "blue",linetype = 1)

Created on 2023-06-19 with reprex v2.0.2
Another potential option is to use the ggnewscale package, e.g.
library(tidyverse)
library(ggnewscale)
plt_regression_line <- function(color = "black", linetype = "dashed"){
list(
ggplot2::geom_smooth(
method = "lm",
se = FALSE,
formula = "y ~ x",
mapping = ggplot2::aes(alpha = "Regression line"),
linetype = linetype,
color = color),
ggplot2::labs(alpha = ""),
ggplot2::scale_alpha_manual(values = c(1,1))
)
}
plt_identity_line <- function(color = "black", linetype = "dashed"){
list(
ggplot2::geom_abline(
mapping = ggplot2::aes(slope = 1, intercept = 0,alpha = "Identity line"),
linetype = linetype,
color = color),
ggplot2::labs(alpha = ""),
ggplot2::scale_alpha_manual(values = c(1,1))
)
}
ggplot(mtcars,aes(qsec,mpg))+
geom_point()+
plt_regression_line(color = "red",linetype = 1) +
ggnewscale::new_scale(new_aes = "alpha") +
plt_identity_line(color = "blue",linetype = 1)

Created on 2023-06-19 with reprex v2.0.2
Do either of these solutions work for your use-case?
