【问题标题】:How to remove lines from legends in ggplot?如何从ggplot中的图例中删除线条?
【发布时间】:2016-10-26 13:59:48
【问题描述】:

我已经阅读了一些关于此的帖子,但没有找到适合我的问题的解决方案。 因为 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)))

最后两行是我在类似问题中找到的解决方案。但是它们要么隐藏所有线型,要么隐藏所有颜色,这是没有用的。

有什么想法吗?

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

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    如果您将show.legend = FALSE 添加到对geom_vline 的调用中,它将不包括垂直线,这应该可以满足您的需求。

    【讨论】:

    • 哇,这么简单...感谢您的快速回复!
    猜你喜欢
    • 2020-01-14
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    相关资源
    最近更新 更多