Johnny5ish
Johnny5ish

Reputation: 295

Problem with multiple series legend in ggplot

I am having trouble getting both line types to show up in my legend.

Here is the data i'm using

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

and the code i've been trying...

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

which give this... enter image description here

My ideal output would have a legend for Salinity with Zone B and D showing the color and solid lines.

Then either additional entries or separate legend with Discharge level showing the line color and the dotted lines.

Upvotes: 1

Views: 56

Answers (1)

stefan
stefan

Reputation: 125373

Making use of the ggnewscale package which allows for multiple color, ... legends you could achieve your desired result like so:

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

Upvotes: 1

Related Questions