如何从ggplot中的图例中删除线条?

时间:2016-10-26 13:59:48

标签: r ggplot2 legend

我已经阅读了一些有关此问题的帖子,但没有为我的问题找到正确的解决方案。 因为geom_vline的虚线是垂直的,所以它也在图例中显示出来。最重要的是,短虚线也得到一个垂直的伙伴,这实际上是没有必要的。 是否可以只获得颜色和类型的水平线?它会让传说更加清晰。

由于我的代码基于大型数据集,因此我在此处制作了一个简单的简短变体。

# 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)))

底部两行是我在类似问题中找到的解决方案。但是它们隐藏了所有的线型或所有颜色,这些都没用。

有什么想法吗?

(我会插入图片,但我不知道我可以把它们放在哪个网站上......)

1 个答案:

答案 0 :(得分:2)

如果您将show.legend = FALSE添加到geom_vline的来电中,则不会包含垂直线,这可以为您提供所需的内容。