如何在图例中添加图例? [英] How to add a legend to hline?
问题描述
我想在图样中添加一个图例.
I'd like to add a legend to hline plot.
我的子集的头看起来像这样
The head of my subset looks like this
Site Date Al
1 Bo6 2014-10-07 152.1
2 Bo1 2014-10-07 157.3
3 Bo3 2014-10-07 207.1
4 Bo4 2014-10-07 184.3
5 Bo5 2014-10-07 23.2
13 Bo6 2014-10-14 96.8
我的代码如下:
require(ggplot2)
require(reshape2)
require(magrittr)
require(dplyr)
require(tidyr)
setwd("~/Documents/Results")
mydata <- read.csv("Metals sheet Rwosnb5.csv")
mydata <- read.csv("Metals sheet Rwosnb5.csv")
L <- subset(mydata, Site =="Bo1"| Site == "Bo2"| Site == "Bo3"| Site == "Bo4"| Site == "Bo5" | Site == "Bo6", select = c(Site,Date,Al))
L$Date <- as.Date(L$Date, "%d/%m/%Y")
I <- ggplot(data=L, aes(x=Date, y=Al, colour=Site)) +
geom_point() +
labs(title = "Total Al in the Barlwyd and Bowydd in Pant-yr-afon sites B4-B9
2014-2015.", x = "Month 2014/2015",
y = "Total concentration (mg/L)") +
scale_y_continuous(limits = c(0, 500)) +
scale_x_date(date_breaks = "1 month", date_labels = "%m")
I + geom_hline(aes(yintercept= 10), linetype = 2, colour= 'red', show.legend =TRUE) +
geom_hline(aes(yintercept= 75.5), linetype = 2, colour= 'blue', show.legend = TRUE)
由于某些原因,图例不起作用-图例有六个站点,其中有一条线.理想情况下,我想要一个标题=限制的图例 标签1(10)= NRW限值,标签2(75.5)=地球化学图谱限值.
For some reason the legend does not work -- the legend has the six sites with a line through them. I would ideally like a legend with title = limit and Label 1 (10) = NRW limit and label 2 (75.5)= Geochemical atlas limit.
推荐答案
您可以使用linetype
美感为水平线制作单独的图例,而不必将其添加到现有图例中.
You can use the linetype
aesthetic to make a separate legend for the horizontal lines rather than adding them to the existing legend.
为此,我们可以将linetype
移到aes
内,同时仍映射到常量.我用了你想要的标签作为常数.可以在scale_linetype_manual
中设置图例名称和使用的线型.我删除了show.legend = TRUE
,以使行不出现在其他图例中.图例颜色在override.aes
中固定.
To do this we can move linetype
inside aes
while still mapping to a constant. I used your desired labels as the constant. The legend name and the line type used can be set in scale_linetype_manual
. I remove show.legend = TRUE
to keep the lines out of the other legend. The legend colors are fixed in override.aes
.
I + geom_hline(aes(yintercept= 10, linetype = "NRW limit"), colour= 'red') +
geom_hline(aes(yintercept= 75.5, linetype = "Geochemical atlas limit"), colour= 'blue') +
scale_linetype_manual(name = "limit", values = c(2, 2),
guide = guide_legend(override.aes = list(color = c("blue", "red"))))
这篇关于如何在图例中添加图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!