ggplot 中多个系列图例的问题

Problem with multiple series legend in ggplot

我无法让两种线型都显示在我的图例中。

这是我使用的数据

structure(list(Year = c(2009L, 2009L, 2010L, 2010L, 2011L, 2011L, 
2012L, 2012L, 2013L, 2013L, 2014L, 2014L, 2015L, 2015L, 2016L, 
2016L, 2017L, 2017L, 2018L, 2018L), Zone = c("B", "D", "B", "D", 
"B", "D", "B", "D", "B", "D", "B", "D", "B", "D", "B", "D", "B", 
"D", "B", "D"), Salinity = c(29.0478299120235, 31.7320374800638, 
25.3940421686747, 28.5938442403368, 30.8545325670498, 32.5533888251052, 
25.0315209561231, 29.4633142361111, 24.7870692757535, 29.272977324263, 
28.3291395752059, 27.6447203874945, 27.4282948073702, 28.6277319754284, 
26.1200853361198, 30.7943264446996, 25.4087317961165, 29.8181971733885, 
22.770421686747, 27.3893364039577), Level = c(2, 4, 1, 2, 4, 
4, 3, 1, 1, 2, 1, 1, 2, 3, 3, 2, 3, 3, 2, 1)), row.names = c(NA, 
-20L), groups = structure(list(Year = 2009:2018, .rows = structure(list(
    1:2, 3:4, 5:6, 7:8, 9:10, 11:12, 13:14, 15:16, 17:18, 19:20), ptype = integer(0), class = c("vctrs_list_of", 
"vctrs_vctr", "list"))), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

以及我一直在尝试的代码...

p <- ggplot(BD_sal, aes(Year)) + 
  geom_line(aes(y = (Salinity), colour = Zone)) + 
  geom_line(aes(y = (as.numeric(forcats::fct_rev(as.factor(Level))))*5, colour = Zone), 
            linetype = "dashed", show.legend = TRUE) +
  scale_y_continuous(
     name = "Salinity (ppt)",
     sec.axis = sec_axis(~./5, name="Discharge Level")) +
  theme_classic()

p

这给...

我的理想输出应该有一个盐度图例,B 区和 D 区显示颜色和实线。

然后是附加条目或单独的图例,放电水平显示线条颜色和虚线。

利用允许多种颜色的 ggnewscale 包,...传说你可以像这样达到你想要的结果:

library(ggplot2)
library(ggnewscale)

ggplot(BD_sal, aes(Year)) +
  geom_line(aes(y = Salinity, colour = Zone), linetype = "solid") +
  scale_color_discrete(name = "Salinity") +
  new_scale_color() +
  geom_line(aes(y = as.numeric(forcats::fct_rev(factor(Level))) * 5, colour = Zone), linetype = "dashed") +
  scale_color_discrete(name = "Discharge") +
  scale_y_continuous(
    name = "Salinity (ppt)",
    sec.axis = sec_axis(~ . / 5, name = "Discharge Level")
  ) +
  theme_classic()