How to remove lines from legends in ggplot?

2019-08-02 07:10发布

I've read a few posts about this, but didn't find the right solution for my problem. Because the dashed line from geom_vline is vertical, it's also shown that way in the legend. On top of that, the short-dashed lines also get a vertical partner which is really not necessary. Is it possible to get only horizontal lines for both the colours and the types? It would make the legend much clearer.

As my code is based on a large dataset, I made a simple short variant 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 a solution I found in a similar question. But they hide either all linetypes or all colours, which isn't useful.

Any ideas?

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

标签: r ggplot2 legend
1条回答
我想做一个坏孩纸
2楼-- · 2019-08-02 07:42

If you add show.legend = FALSE to the call to geom_vline it will not include the vertical line, which should give you what you want.

查看更多
登录 后发表回答