[R] dual y-axis for ggplot

John miaojpm at gmail.com
Thu Oct 12 09:14:00 CEST 2017


Sorry let me clarify.
If I modify the line
 p <- p + geom_line(aes(y = air_temp, colour = "Temperature"))
by
p <- p + geom_line(aes(y = air_temp, colour = "Temperature", linetype
="Temperature"))
and
p <- p + geom_line(aes(y = rel_hum/5, colour = "Humidity"))
by
p <- p + geom_line(aes(y = rel_hum/5, colour = "Humidity",
linetype="Humidity"))
and
p <- p + scale_linetype_manual(values = c("twodash", "solid")),

I will have two lines with different color and different line type,

but I will have two legends  (one with blue/red,solid, the other with two
dash/solid, black ).

How can I have only one legend with blue/two dash and red/solid?




2017-10-12 0:06 GMT-07:00 John <miaojpm at gmail.com>:

> 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