Reputation: 1284
The plot below is to create a ggplot in which I show the relationship between two variables according to the raw data (points) and according to two different models (m1
and m3
), from which I extract the coefficients and I drow two continuous lines. The grey line is just to show a relationship of 1:1.
line_colors <- RColorBrewer::brewer.pal(7, "Reds")[c(2,4,6)]
line_colors
Plot_a <- ggplot(Todo.6min, aes(x=VeDBA.V13AP, y=VeDBA.X16, colour=ID)) +
geom_point(size=1.5,alpha=0.2) +
geom_abline(aes(slope=1,intercept=0),linetype="dashed",color="grey52",size=1.5) +
theme_bw() +
theme(strip.background=element_blank(),
axis.title.x =element_blank(),
axis.title.y =element_blank(),
axis.text.x = element_text(angle = 0, hjust = 0.5,size = 15),
axis.text.y = element_text(angle = 0, hjust = 0.5,size = 15),
axis.line = element_line(),
panel.grid.major= element_blank(),
panel.grid.minor = element_blank(),
legend.position = "right",
legend.text=element_text(size=18),
legend.title = element_text(size=19, face = "bold"),
legend.key=element_blank(),
panel.border = element_blank(),
strip.placement = "outside") +
guides(color=guide_legend(override.aes=list(fill=NA)))
Plot_a
Plot_b <- Plot_a +
geom_abline(aes(linetype = "m1"),slope = fixef(mod2b)[2] , intercept = fixef(mod2b)[1], color = line_colors[1], size=1.5) +
geom_abline(aes(linetype = "m3"),slope = fixef(mod2d)[2] + fixef(mod2d)[3], intercept = fixef(mod2d)[1], color = line_colors[2], size=1.5) +
scale_linetype_manual(values = c(m1 = "solid", m3 = "solid"),labels = c(m1 = "m1", m3 = "m3")) +
labs(color = "ID", linetype = expression(Model)) +
guides(linetype = guide_legend(override.aes = list(color = line_colors)))
Plot_b
My doubt is why I do not get a legend for the continuous lines although I used scale_linetype_manual
for indicating that I wanted a legend in which appears "m1" and "m3" as legend.text
.
Does anyone know where is the mistake?
Upvotes: 1
Views: 507
Reputation: 37943
My suggestion would be to manually populate the mapping of geom_abline()
, and then cut the data so that it matches the number of lines you're drawing. Illustrated below with an inbuilt dataset.
library(ggplot2)
ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
geom_abline(aes(linetype = c("m1", "m3"),
slope = c(0.5, 0.75),
intercept = c(0, 0.5)),
data = iris[1:2,])
Created on 2020-11-06 by the reprex package (v0.3.0)
For your use case you'd have to substute slope = c(0.5, 0.75)
by slope = c(fixef(mod2b)[2], fixef(mod2d)[2])
, etc.
Upvotes: 1