user11841097
user11841097

Reputation: 79

How to remove boxes around ggplot2 legend labels

I have a line chart with an ribbon between first and third quartil of the data. When I plot the data with ggplot2 I get boxes around the labels which I don't get rid of whatever I try (i. e. theme(legend.background=element_blank()) or guides(guides_legend) with override). dataframe Here are the first rows of my dataset and the code:

  mutate(code_range = fct_reorder2(code_range, year, order)) %>% 
  ggplot(aes(x=year, y=value, group=code_range, color=code_range)) +
  geom_ribbon(aes(ymin = min_range, 
                  ymax = max_range), fill = "grey70", alpha=0.1) +
  geom_line(size=1) +
  labs(title="Title", 
       subtitle=paste0("subtitle"),
       x="",y="",
       caption="Source") +
  scale_colour_manual(values = c("min" = "#878787", "q1" = "#B5B5B5", "median" = "#27408B", 
                                 "q3" = "#B5B5B5", "max" = "#878787")) +
  scale_fill_manual(values = c("min" = "#FFFFFF", "q1" = "#B5B5B5", "median" = "#27408B", 
                               "q3" = "#B5B5B5", "max" = "#878787")) +
  theme_opts +
  theme(legend.title = element_blank(), 
        legend.position = "bottom") +
  theme(legend.background=element_blank()) 
plot 

Does anybody know a solution how to remove those boxes?

Plot

Upvotes: 1

Views: 478

Answers (2)

tjebo
tjebo

Reputation: 23737

Another option is to move the color aesthetic only to geom_line

library(ggplot2)

p <- ggplot(iris, aes(Sepal.Length, Petal.Width, color = Species)) +
  geom_smooth()

df_p <- layer_data(p)
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

## something similar to your plot
ggplot(df_p, aes(color = as.character(group))) + 
  geom_ribbon(aes(x = x, ymin = ymin, ymax = ymax)) +
  geom_line(aes(x, y))

## change the location of your color aesthetic to geom_line only
## you need to add a grouping aesthetic into the ribbon call
ggplot(df_p) + 
  geom_ribbon(aes(x = x, ymin = ymin, ymax = ymax, group = as.character(group))) +
  geom_line(aes(x, y, color = as.character(group)))

Created on 2023-01-02 with reprex v2.0.2

Upvotes: 3

stefan
stefan

Reputation: 124083

The boxes around the legend keys reflect the geom_ribbon. To remove them you could add show.legend=FALSE to geom_ribbon.

Using some fake example data:

library(ggplot2)

df <- data.frame(
  year = 2005:2020,
  value = 1:16,
  min_range = 1:16 - 1,
  max_range = 1:16 + 1
)

base <- ggplot(df, aes(year, value, color = "median")) +
  geom_line() +
  scale_colour_manual(values = c(
    "min" = "#878787", "q1" = "#B5B5B5", "median" = "#27408B",
    "q3" = "#B5B5B5", "max" = "#878787"
  ))

First replicating your issue:

base +
  geom_ribbon(aes(ymin = min_range, ymax = max_range), fill = "grey70", alpha = 0.1)

And second using show.legend = FALSE:

base +
  geom_ribbon(aes(ymin = min_range, ymax = max_range), fill = "grey70", alpha = 0.1, show.legend = FALSE)

Upvotes: 3

Related Questions