R ggplot图例格式为geom_hline

时间:2018-06-29 14:27:46

标签: r ggplot2 legend

以下是数据的开头:

LocationName Section Event_Date           Year Species_Code  Area YOYpop ADTpop TOTpop YOYmnwt ADTmnwt
  <chr>        <chr>   <dttm>              <dbl> <chr>        <dbl>  <dbl>  <dbl>  <dbl>   <dbl>   <dbl>
1 Cosby Creek  2       2013-06-04 00:00:00  2013 BKT           410       9     73     82     2.8    25.3
2 Cosby Creek  2       2014-06-03 00:00:00  2014 BKT           693.     62     34     92     1.7    36.1
3 Cosby Creek  2       2015-06-12 00:00:00  2015 BKT           454.     63     46    109     2.3    28.4
4 Cosby Creek  2       2016-06-13 00:00:00  2016 BKT           506.     20     56     76     3.2    30.2
5 Cosby Creek  2       2017-06-12 00:00:00  2017 BKT           442.     13     19     32     6.2    45.3
6 Cosby Creek  2       2000-06-01 00:00:00  2000 BKT           563.     33     37     72     3      32.5

代码如下:

library(tidyverse)    
select(Year, YOYBiom, ADTBiom) %>%
  gather(key = Age, value = Biomass, YOYBiom, ADTBiom)
  ggplot(FISH.biom, aes(x = Year, y = Biomass)) +
  geom_point(aes(colour = Age)) +
  scale_colour_manual(values = c("orange", "blue")) +
  geom_hline(aes(yintercept = c(quantile(FISH$YOYBiom, 0.025)), linetype = "YOY Lower CL"), colour = "blue") +
  geom_hline(aes(yintercept = c(quantile(FISH$YOYBiom, 0.975)), linetype = "YOY Upper CL"), colour = "blue") +
  geom_hline(aes(yintercept = c(quantile(FISH$ADTBiom, 0.025)), linetype = "ADT Lower CL"), colour = "orange") +
  geom_hline(aes(yintercept = c(quantile(FISH$ADTBiom, 0.975)), linetype = "ADT Upper CL"), colour = "orange") +
  labs(title = "Annual Biomass", subtitle = "(Cosby Creek)", x = "Year", y = "Biomass (kg/ha)")+ #adds labels
  theme_bw(base_size = 10)

这是输出图:

enter image description here

如您所见,存在两个问题。我希望:

  1. 使geom_hline的图例中的颜色与图形上的颜色匹配
  2. 用更有意义的名称代替geom_hline的图例标题/标签,而不是'linetype'

我在这里找到了帮助:How to add a legend to hline?

但是我碰壁了。

谢谢

1 个答案:

答案 0 :(得分:0)

您需要使用scale_linetype_manual()手动设置图例