Peter Jordanson
Peter Jordanson

Reputation: 51

How to make ggplot show the linetype and line colour in the legend?

How can I make the legend show not only the line colour, but also the linetype? I want the grey line next to "y = x" to be dashed, like in the plot.

Here is the code I used to make the plot, with some sample data:

# Sample data
df_REM24_Q <- data.frame(lngini_eurostat = sort(runif(10, 3, 4)),
                   fit_augment = sort(runif(10, 3, 4)))

ggplot(df_REM24_Q, aes(x=lngini_eurostat, y=fit_augment)) + 
 geom_point(size=1.5, shape=16, alpha=1) + 
 geom_smooth(method="lm", formula = y ~ x, aes(colour="blue")) +
 geom_abline(linetype = 2, aes(slope = 1, intercept = 0, colour="red"), show.legend = FALSE) + 
 labs(x="Observed ln(Gini)", y="Predicted ln(Gini)") + 
 theme_few() + 
 scale_colour_manual(name='Legend',
                  labels = c(TeX("Panel regression: $R^2 = 0.873$"), TeX("$y = x$")), 
                  values = c("#0072c3", "#737373")) + 
 scale_linetype_manual(name = 'Legend', 
                    labels = c("Panel regression", "y = x"), 
                    values = c("#0072c3", "#737373")) + 
 theme(legend.position = c(.2, .85), 
    legend.key = element_rect(fill = "white", colour = "black", size=0.3), 
    legend.title = element_text(face = "bold"),
    legend.text.align = 0) +
 guides(color = guide_legend(override.aes = list(fill = NA)), linetype = guide_legend(override.aes = list(fill = NA)))  

The plot: enter image description here

Upvotes: 0

Views: 363

Answers (1)

Andy Baxter
Andy Baxter

Reputation: 7636

You can override linetype in your last line call to override.aes:

library(ggplot2)
library(ggthemes)
library(latex2exp)

df_REM24_Q <- data.frame(lngini_eurostat = sort(runif(10, 3, 4)),
                         fit_augment = sort(runif(10, 3, 4)))

ggplot(df_REM24_Q, aes(x=lngini_eurostat, y=fit_augment)) + 
  geom_point(size=1.5, shape=16, alpha=1) + 
  geom_smooth(method="lm", formula = y ~ x, aes(colour="blue")) +
  geom_abline(linetype = 2, aes(slope = 1, intercept = 0, colour="red"), show.legend = FALSE) + 
  labs(x="Observed ln(Gini)", y="Predicted ln(Gini)") + 
  theme_few() + 
  scale_colour_manual(name='Legend',
                      labels = c(TeX("Panel regression: $R^2 = 0.873$"), TeX("$y = x$")), 
                      values = c("#0072c3", "#737373")) + 
  theme(legend.position = c(.2, .85), 
        legend.key = element_rect(fill = "white", colour = "black", size=0.3), 
        legend.title = element_text(face = "bold"),
        legend.text.align = 0) +
  guides(color = guide_legend(override.aes = list(fill = NA,
                                                  linetype = c(1, 2)))) 

I also removed the scale_linetype_manual line as that was no longer necessary - unless you do mean to create two legends, one with varying linetype and one with varying colour?

Created on 2022-05-09 by the reprex package (v2.0.1)

Upvotes: 1

Related Questions