Reputation: 51
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.
Upvotes: 2
Views: 442
Reputation: 41437
First you should set show.legend = FALSE
in your geom_abline
. After that you can use this code to set white background in your boxes in the legend: guides(color = guide_legend(override.aes = list(fill = NA)), linetype = guide_legend(override.aes = list(fill = NA)))
. You can use the following code (ps I created random data):
library(tidyverse)
library(ggthemes)
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"), show.legend = FALSE) +
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")) +
guides(color = guide_legend(override.aes = list(fill = NA)), linetype = guide_legend(override.aes = list(fill = NA)))
Output:
df_REM24 <- data.frame(lngini_eurostat = sort(runif(10, 3, 4)),
fit_augment = sort(runif(10, 3, 4)))
Upvotes: 2
Reputation: 7540
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 reprex package (v2.0.1)
Upvotes: 1