[R] dual y-axis for ggplot

John miaojpm at gmail.com
Thu Oct 12 09:06:40 CEST 2017


Hi,

   To my knowledge, an excellent of ggplot with a second y-axis is

https://rpubs.com/MarkusLoew/226759

   In this example, the author uses two colors for the two lines, but the
line shapes are the same -- both are solid. Could each line have its own
color as well as its own shape? For example, can I make the red line with
the linetype "twodash", while the blue line with the linetype "solid"?
   For convenience, I copied the codes as follows.

########
p <- ggplot(obs, aes(x = Timestamp))
  p <- p + geom_line(aes(y = air_temp, colour = "Temperature"))

  # adding the relative humidity data, transformed to match roughly the
range of the temperature
  p <- p + geom_line(aes(y = rel_hum/5, colour = "Humidity"))

  # now adding the secondary axis, following the example in the help file
?scale_y_continuous
  # and, very important, reverting the above transformation
  p <- p + scale_y_continuous(sec.axis = sec_axis(~.*5, name = "Relative
humidity [%]"))

  # modifying colours and theme options
  p <- p + scale_colour_manual(values = c("blue", "red"))
  p <- p + labs(y = "Air temperature [°C]",
                x = "Date and time",
                colour = "Parameter")
  p <- p + theme(legend.position = c(0.8, 0.9))
p
########

   Thanks,

John

	[[alternative HTML version deleted]]



More information about the R-help mailing list