Using ggplot2
Here is solution using an example data.frame:
# Build dummy data
data <- data.frame(
time = seq(c(ISOdate(2000,3,20)), by = "min", length.out = 100),
temperature = runif(100, 0,30),
temperature2 = runif(100,0,30),
depth = runif(100,0,1200)
)
ggplot(data) +
geom_line(aes(x=time, y=depth, color="Depth"), size=1) +
geom_line(aes(x=time, y=temperature*40-30, color="Perit. Temp"), size=1) +
geom_line(aes(x=time, y=temperature2*40-30, color="Ambien Temp."), size=1) +
scale_x_datetime(position="top") +
scale_y_continuous(
name = "Depth (m)",
trans="reverse",
sec.axis = sec_axis(trans= ~.*-1/40+30, name="Temperature (C)")) +
labs(x = "Time (local)") +
theme_bw() +
scale_colour_manual(name="Legend",values=c("Depth"="black", "Ambien Temp."="blue", "Perit. Temp"="red") ) +
theme(legend.position = c(0.87, 0.25))
If you want to use a secondary y-axis, you have to use a transformation from the original y-axis (the point in the formula indicates the value of original y-axis) and apply the reverse transformation on your data which you want to use for the secondary y-axis.
If you want to use the x-axis on the top you have to take care to use the correct function, e.g. here it is scale_x_datetime
because we ware using a datetime.
Also note, that the names to create your legend (scale_colour_manual
) must be exactly the same as in your aes
-argument.
