Home > Blockchain >  Why does the ggplot legend show both line colour and linetype?
Why does the ggplot legend show both line colour and linetype?

Time:05-05

I want the legend to show a blue solid line for "Panel regression", and a grey dashed line for "y = x". Why does it show the diagonal dashed lines in the legend?

 ggplot(df_REM24, 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"))   
  labs(x="Observed ln(Gini)", y="Predicted ln(Gini)")   
  theme_few()   
  scale_colour_manual(name='Legend',
                      labels = c("Panel regression", "y = x"), 
                      values = c("#0072c3", "#737373"))   
  theme(legend.position = c(.15, .9), 
        legend.key = element_rect(fill = "white", colour = "black", size=0.3), 
        legend.title = element_text(face = "bold"))

Also, I set the legend.key fill to white but it remains in grey.

the plot I currently have

CodePudding user response:

Should work with the missing bracket and without the aes in geom_smooth per this reproducible example with made-up data:

library(tidyverse)

tibble(x = rep(seq(2, 16, 1), 2),
       y = abs(rnorm(30, 10, 10)),
       colour = rep(c("fore", "hind"), 15)
) |> 
  ggplot(aes(x, y, colour = colour))  
  geom_point()  
  geom_smooth(colour = "blue")  
  theme(legend.key = element_rect(fill = "white"))
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Created on 2022-05-04 by the enter image description here

Data

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