How to remove lines from legends in ggplot?

I read a few posts about this, but could not find the right solution for my problem. Since the dotted line from geom_vline is vertical, it is also shown in this way in the legend. In addition, short dashed lines also get a vertical partner that is not really needed. Is it possible to get only horizontal lines for colors and types? That would make the legend much clearer.

Since my code is based on a large dataset, I made a simple short version to show here.

# data (example)

meetdagen1 <- as.Date(c("2016-06-01", "2016-06-28", "2016-07-17", "2016-08-03", "2016-08-30", "2016-09-10"))
maxtemp    <- c(20, 22, 28, 24, 23, 22)
meantemp   <- maxtemp - 2
mintemp    <- meantemp - 2

meetdagen2 <- c(meetdagen1, as.Date(c("2016-09-29", "2016-10-12", "2016-11-01")))
maxtemp2   <- c(maxtemp, 20, 17, 19)
meantemp2  <- maxtemp2 - 2
mintemp2   <- meantemp2 - 2

# dataframes for ggplot

df  <- data.frame(meetdagen1, meantemp, mintemp, maxtemp)
df2 <- data.frame(meetdagen2, meantemp2, mintemp2, maxtemp2)

# plot

ggplot() +
  xlab("Time (months)") + 
  ylab("Daily temperature (°C)") +
  scale_x_date(date_labels = "%b %d", date_breaks = "1 month") + 
  geom_line(data = df, aes(x = meetdagen1, y = maxtemp, colour = "max.temp"), size = 0.75) +
  geom_line(data = df, aes(x = meetdagen1, y = meantemp, colour = "gem.temp"), size = 0.75) +
  geom_line(data = df, aes(x = meetdagen1, y = mintemp, colour = "min.temp"), size = 0.75) +
  geom_line(data = df2, aes(x = meetdagen2, y = maxtemp2, colour = "max.temp", lty = "prediction"), size = 0.75) +
  geom_line(data = df2, aes(x = meetdagen2, y = meantemp2, colour = "gem.temp", lty = "prediction"), size = 0.75) +
  geom_line(data = df2, aes(x = meetdagen2, y = mintemp2, colour = "min.temp", lty = "prediction"), size = 0.75) +
  geom_vline(aes(xintercept = as.numeric(Sys.Date()), lty = "today"), size = 0.75) +
  scale_colour_manual("", values = c(max.temp = "firebrick2", gem.temp = "grey20", min.temp = "royalblue3")) +
  scale_linetype_manual("", values = c(prediction = 3, today = 5)) #+
  #guides(colour = guide_legend(override.aes = list(linetype = 0))) +
  #guides(lintype = guide_legend(override.aes = list(colour = NA)))

The bottom two lines are the solution I found in a similar question. But they hide all types of lines or all colors, which is not useful.

Any ideas?

(I would insert images, but I have no idea which website I can put them on ...)

+1
1

show.legend = FALSE geom_vline, , , .

+2

All Articles