Remove Fill Around Legend Key in Ggplot

Remove fill around legend key in ggplot

You get this grey color inside legend keys because you use stat_smooth() that as default makes also confidence interval around the line with some fill (grey if fill= isn't used inside the aes()).

One solution is to set se=FALSE for stat_smooth() if you don't need the confidence intervals.

  +stat_smooth(method = "loess", formula = y ~ x, level=0, size = 1, 
aes(group = gender, colour=gender),se=FALSE)

Another solution is to use the function guides() and override.aes= to remove fill from the legend but keep confidence intervals around lines.

  + guides(color=guide_legend(override.aes=list(fill=NA)))

Remove fill around legend key for geom_ribbon in ggplot2

Great question! A potential solution is to include show.legend = FALSE and also remove the legend key background using theme() (each of these actions won't 'work' on their own), e.g.

library(tidyverse)
# install.packages("ggeffects")
library(ggeffects)

fit <- lm(mpg ~ hp*disp, data= mtcars)

me <- ggeffect(fit,
ci.lvl = .95,
type = "fe",
terms = c("hp", "disp"))

ggplot(data = me,
mapping = aes(x = x, y = predicted, linetype = group)) +
geom_line() +
geom_ribbon(aes(ymin = conf.low,
ymax = conf.high),
alpha = .5, show.legend = FALSE) +
theme(legend.key = element_blank())

Created on 2021-08-24 by the reprex package (v2.0.0)

Does this answer translate to your actual data?

Remove legend in ggplot

I couldn't run your code, but I rebuilt it with iris.

Like Matt suggested, one thing would be, remove fill=F:

ggplot(data=iris, aes(x = SepalLength , y = PetalLength, group=Name)) +
geom_point() +
geom_line() +
stat_smooth(method = "loess",se = T, aes(color=Name)) +
geom_ribbon(aes(ymin = 1, ymax = 3),alpha = 1/5) +
scale_x_continuous(breaks = 0:2, labels = c(0, 6, 12))

Or if you need it for some reason, use guides(fill="none"):

ggplot(data=iris, aes(x = SepalLength , y = PetalLength, group=Name)) +
geom_point() +
geom_line() +
stat_smooth(method = "loess",se = T, aes(color=Name)) +
geom_ribbon(aes(ymin = 1, ymax = 3, fill=FALSE),alpha = 1/5) +
scale_x_continuous(breaks = 0:2, labels = c(0, 6, 12)) +
guides(fill="none")

Output:

Sample Image

ggplot2 make legend key fill transparent

You could trick it if you want. Add a second geom_smooth(). The first with a confidence band and you don't show the legend. With the second one you remove the band but show the legend.

df$Color <- "Red"
df1 <- df
(plot = ggplot() +
geom_smooth(data=df, aes(data1, data2,colour=Color), se = TRUE, show.legend = FALSE) +
geom_smooth(data=df1, aes(data1, data2,colour=Color), se=FALSE) +
geom_abline(intercept=0, slope=1,linetype="dashed", color = "black")+
scale_x_continuous(expand=c(0,0), limits=c(0,100)) +
scale_y_continuous(expand=c(0,0), limits=c(0,100))+
theme_classic()+
labs(y="data2", x="data1",
title="sample 1 data1 vs data2") +
theme(plot.title = element_text(size=18, face="bold"),
legend.key = element_rect(colour = "transparent", fill = "white"),
legend.justification = c(1,0), legend.position = c(1,0))+
scale_color_discrete(name="Sample"))

Sample Image

How to apply legend.key backround transparent in ggplot?

You need to either add se = FALSE or remove stat_smooth(method = "loess") to remove the grey filled background in vehicle model legend keys.

library(ggplot2)

p <- ggplot(data = mpg, mapping = aes(x = cty, y = hwy, colour = class)) +
geom_point(aes(size = displ), alpha = 0.5) +
stat_smooth(method = "loess", se = FALSE) + # Add se = FALSE
scale_size_continuous(range = c(4, 10)) +
facet_wrap(~year, ncol = 2) +
labs(
x = "distance per gallon in city", y = "distance per gallon in highway",
title = "fuel consumption and model", size = "displacement", colour = "vehicle model"
)

p +
theme(
plot.background = element_blank(),
panel.background = element_rect(fill = "transparent", colour = "gray"),
panel.border = element_rect(fill = "transparent", colour = "black"),
axis.text = element_text(color = "black"),
panel.grid.major = element_line(colour = "grey", linetype = "dashed"),
strip.background = element_blank(),
panel.spacing.x = unit(4, "mm"),
legend.box.background = element_rect(fill = "blue", colour = "transparent"),
legend.key = element_rect(fill = "transparent", colour = "transparent")
)

p +
theme(
plot.background = element_rect(fill = "transparent", colour = "transparent"),
panel.background = element_rect(fill = "transparent", colour = "gray"),
panel.border = element_rect(fill = "transparent", colour = "black"),
axis.text = element_text(color = "black"),
panel.grid.major = element_line(colour = "grey", linetype = "dashed"),
strip.background = element_rect(fill = "transparent", colour = "transparent"),
panel.spacing.x = unit(4, "mm"),
legend.background = element_blank(),
legend.box.background = element_blank(),
legend.key = element_blank()
)

Created on 2018-11-03 by the reprex package (v0.2.1.9000)

Removing the border of legend symbol

I think geom_ribbon was the problem. If we take its color & fill out of aes, everything looks fine

library(ggplot2)

# Some random data
x <- seq(1: 10)
y_pred <- runif(10, min = -10, max = 10)
y_obs <- y_pred + rnorm(10)
# Faking a CI
Lo.95 <- y_pred - 1.96
Hi.95 <- y_pred + 1.96
my_df <- data.frame(x, y_pred, y_obs, Lo.95, Hi.95)

m1 <- ggplot(my_df, aes(x = x, y = y_pred)) +
geom_point(aes(x = x, y = y_obs, colour = "Actual"), size = 3) +
geom_line(aes(colour = "Forecasted"), size = 1.2) +
geom_ribbon(aes(x = x, ymin = Lo.95, ymax = Hi.95),
fill = "grey30", alpha = 0.2) +
scale_color_manual("Legend",
values = c("blue", "red"),
labels = c("Actual", "Forecasted")) +
guides( color = guide_legend(
order = 1,
override.aes = list(
color = c("blue", "red"),
fill = c("white", "white"),
linetype = c("blank", "solid"),
shape = c(19, NA)))) +
theme_bw() +
# remove legend key border color & background
theme(legend.key = element_rect(colour = NA, fill = NA),
legend.box.background = element_blank())
m1

As we leave Confidence Interval out of aes, we no longer have its legend. One workaround is to create an invisible point and take one unused geom to manually create a legend key. Here we can use size/shape (credit to this answer)

m2 <- m1 +
geom_point(aes(x = x, y = y_obs, size = "Confidence Interval", shape = NA)) +
guides(size = guide_legend(NULL,
order = 2,
override.aes = list(shape = 15,
color = "lightgrey",
size = 6))) +
# Move legends closer to each other
theme(legend.title = element_blank(),
legend.justification = "center",
legend.spacing.y = unit(0.05, "cm"),
legend.margin = margin(0, 0, 0, 0),
legend.box.margin = margin(0, 0, 0, 0))
m2

Created on 2018-03-19 by the reprex package (v0.2.0).

Remove box and points in legend

Your ggplot code is a little bit messy, particularly for the ribbon. For example the fill aestetic is both mapped to the effect variable and set to a color value (#C0CCD9).

To remove the boxes in the legend key you need to use legend.key in theme but it works only after cleaning your ggplot code.

To avoid unnecessary repetitions I have moved severeal aestetics to the first ggplot call so that ggplot use them as default for the subsequent geom_XX calls.

ggplot(pdat1, aes(x = temp, y = value, group = effect)) + 
geom_ribbon(aes(ymax = value_max, ymin = value_min), fill = "#C0CCD9", alpha = 0.5 ) +
geom_line(aes(color = effect)) +
geom_point(aes(color = effect), size = 0.5) +
ylab("Y") + xlab("X") +
guides(color = guide_legend(keywidth = 2, keyheight = 1,
override.aes = list(size = 1, shape = NA))) +
facet_wrap(~type) +
theme_bw() +
theme(legend.key = element_rect(fill = NA, color = NA))

How to avoid the box in legend key when using aes(fill=kind) in both geom_bar and geom_smooth?

You could add show.legend = FALSE in your geom_smooth:

library(tidyverse)

mma <- data.frame(kind=c(rep('A',100), rep('BB', 100), rep('CC',100)),
group=c(rep(seq(0.1, 10, by=0.1),3)),
frac=runif(n=300, min=0, max=1))

### pic
wd <- 0.05
posa <- position_dodge(width=wd)
ggplot(data=mma, aes(x=group, y=frac, group=kind))+
geom_bar(aes(fill=kind), stat='identity', position=posa, width=wd)+
geom_smooth(aes(fill=kind, color=kind), method="loess", span=0.15, size=0.5, show.legend = FALSE)+
labs(x="Time", y="Populations")+
## default mina.png
guides(fill=guide_legend(ncol=3, byrow=TRUE), color="none")+ # minb.png
## guides(color=guide_legend(ncol=3, byrow=TRUE), fill="none")+ # minc.png
theme(legend.position=c(0.66, 0.92),
legend.key.size=unit(0.56, 'lines'))
#> `geom_smooth()` using formula 'y ~ x'

Created on 2022-04-28 by the reprex package (v2.0.1)



Related Topics



Leave a reply



Submit