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 my model (dashed lines, each one for different ID).
Plot_a <- ggplot(Todo.6min, aes(x=VeDBA.V13AP, y=VeDBA.X16, colour=ID)) +
geom_point(size=1.5,alpha=0.2) +
geom_line(aes(y=predict(mod3.6min,df.6min), group=ID), size=3, alpha=0.6, linetype="dashed") +
geom_abline(aes(slope=1,intercept=0),linetype="dashed",color="grey52",size=1.5) +
theme_bw() +
theme(legend.text=element_text(size=18),
legend.title = element_text(size=19, face = "bold"),
legend.key=element_blank()) +
guides(color=guide_legend(override.aes=list(fill=NA)))
Plot_a
Then, I add some extra lines from a different model and I colour those lines using a palette of colours from RColorBrewer
. As you can see, I include a second legend relative to this second model in which appears as legend.title "n.V13AP" and as legend.text "Low","Medium" and "High". The dark red colour should correspond to the nV13AP
level High
, and the less intense red colour should correspond to the nV13AP
level Low
.
line_colors <- RColorBrewer::brewer.pal(7, "Reds")[c(2,4,6)]
line_colors
Plot_a.2 <- Plot_a +
geom_line(aes(y=predict(mod3.6min_gls,df.6min_low.n), linetype = "Low"), color = line_colors[1], size=1.5, alpha=1) +
geom_line(aes(y=predict(mod3.6min_gls,df.6min_medium.n), linetype = "Medium"), color = line_colors[2], size=1.5, alpha=1) +
geom_line(aes(y=predict(mod3.6min_gls,df.6min_high.n), linetype = "High"), color = line_colors[3], size=1.5, alpha=1) +
scale_linetype_manual(values = c(Low = "solid", Medium = "solid", High = "solid"),labels = c(Low = "Low", Medium = "Medium", High = "High")) +
labs(color = "ID", linetype = "nV13AP") +
guides(linetype = guide_legend(override.aes = list(color = line_colors)))
Plot_a.2
However, as you can observe, the colour assignment in the nV13AP
legend is not correct, and I do not know why. Additionaly, the order of the nV13AP
levels is not as I indicated in scale_linetype_manual
. The order in the legend is High
/Low
/Medium
while I would like to have either High
/Medium
/Low
or Low
/Medium
/High
.
Does anyone know where is the mistake? I checked that the colours assignment was wrong changing the values of the High
line and observing which line changed in the plot, and I observed that was the dark red line which changed. So the light red colour for High
in the legend is wrong!.
Upvotes: 0
Views: 123
Reputation: 125038
The issue is that when using guide_legend
you have to put pass color
a vector of colors in the order they appear in the legend, i.e. the "High" color should come first, "Low" second, ... As you provided no data, I could not check but
guides(linetype = guide_legend(override.aes = list(color = line_colors[c(3, 1, 2)]))
should give you the right colors for your linetype legend.
Upvotes: 1