Rosalie Bruel
Rosalie Bruel

Reputation: 1493

ggplot: show the legend for fill only once

I am plotting together two datasets:

I am trying to edit the legend for a plot, such as the background for the "alpha" legend (Number of monitoring sites) is not purple (just transparent).

Here is a code to reproduce my data format and the figure:

# Data table with similar format to what I have
dt2 <- dt <- data.frame(x = rep(1:20, 10),
                 y = factor(rep(LETTERS[1:10], each = 20)),
                 alpha = factor(sample(1:5, size = 40, replace = TRUE)))

# Removing some values in dt2 to match the format of my table
dt2$x[c(1:10, 21:25, 60:65, 81:83, 135:143)] <- NA
# No difference in alpha in dt2
dt2$alpha <- 3

# Plot
ggplot() +
  geom_line(dt2, mapping = aes(x, y, fill = "Weather available"), color = "#DCD0FF",lwd = 3, show.legend = TRUE)  + # add dummy fill
  geom_point(dt, mapping = aes(x, y, alpha = alpha)) +
  labs (x = "Date", y = "Site") + 
  guides(alpha=guide_legend(title="number of monitoring stations", nrow = 2, byrow = TRUE, order = 2),
         fill = guide_legend(title = "", order = 1)) 

output figure

Thanks in advance for you help!

Upvotes: 0

Views: 201

Answers (1)

teunbrand
teunbrand

Reputation: 37913

You can set override.aes = list(linetype = NA) to remove the line from the alpha legend. Example below:

library(ggplot2)

# Data table with similar format to what I have
dt2 <- dt <- data.frame(x = rep(1:20, 10),
                        y = factor(rep(LETTERS[1:10], each = 20)),
                        alpha = factor(sample(1:5, size = 40, replace = TRUE)))

# Removing some values in dt2 to match the format of my table
dt2$x[c(1:10, 21:25, 60:65, 81:83, 135:143)] <- NA
# No difference in alpha in dt2
dt2$alpha <- 3

# Plot
ggplot() +
  geom_line(dt2, mapping = aes(x, y, fill = "Weather available"), 
            color = "#DCD0FF",lwd = 3, show.legend = TRUE)  + # add dummy fill
  geom_point(dt, mapping = aes(x, y, alpha = alpha)) +
  labs (x = "Date", y = "Site") + 
  guides(alpha=guide_legend(title="number of monitoring stations", 
                            nrow = 2, byrow = TRUE, order = 2,
                            override.aes = list(linetype = NA)),
         fill = guide_legend(title = "", order = 1)) 
#> Warning: Ignoring unknown aesthetics: fill
#> Warning: Using alpha for a discrete variable is not advised.
#> Warning: Removed 33 row(s) containing missing values (geom_path).

Created on 2021-04-16 by the reprex package (v1.0.0)

Upvotes: 2

Related Questions