Drawing a 3 axis graph in ggplot2 with r

Thegasman2000

https://imgur.com/a/fYGgpu7

I am trying to recreate a graph such as these below in ggplot2. I have been looking for 3 axis and seem to be getting 3d visualizations which is clearly not what I need so my googlefu has let me down. My data is very simple: https://imgur.com/a/eM8tKAG With the CTD column determining a different graph.

I guess my main issue is the scaling of the axis. My y axis is Depth. It is common to inverse this value as it places the surface of the water at the top.

Allan Cameron

It's considered suboptimal by many (myself included) to have even 2 axes on the same dimension of a plot. There are simply better ways of presenting the same information. It is possible to have a second axis in ggplot, but if you want a third you'll have to create it yourself:

ggplot(df, aes(Salinity, Depth)) + 
  geom_line(color = "green4") +
  geom_line(aes(x = (Temperature - 8.25) * 15 + 29), color = "red3") +
  geom_line(aes(x = Silicate * 0.3 + 24.5), col = "deepskyblue3") +
  annotate(geom = "text", x = seq(15, 27, 3) * 0.3 + 24.5, y = -0.5, 
                label = seq(15, 27, 3), col = "deepskyblue3", size = 3.1) +
  annotate(geom = "text", color = "deepskyblue3", x=30.87, y = -1.5,
           label = "Silicates") +
  geom_hline(yintercept = 0, color = "deepskyblue3") +
  scale_x_continuous(sec.axis = sec_axis(name = "Temperature", 
     trans = function(x) {
          (x - 28) / 15 + 8.25
       })) +
  coord_cartesian(ylim = c(-2, 20), clip = "off") +
  theme_minimal() +
  theme(plot.margin = margin(10, 10, 50, 10),
        axis.text.x.top = element_text(colour = "red3"),
        axis.title.x.top = element_text(colour = "red3"),
        axis.ticks.x.top = element_line(color = "red3"),
        axis.line.x.top = element_line(color = "red3"),
        axis.text.x.bottom = element_text(colour = "green4"),
        axis.title.x.bottom = element_text(colour = "green4"),
        axis.ticks.x.bottom = element_line(color = "green4"),
        axis.line.x.bottom = element_line(colour = "green4"),
        axis.line.y.left = element_line())

enter image description here


Data transcribed from OP

df <- data.frame(CTD = c(1, 1, 1, 2, 2),
                 Depth = c(17.78, 3.89, 1.44, 13.23, 1.34),
                 Temperature = c(8.28, 8.31, 8.49, 8.25, 8.31),
                 Salinity = c(31.9, 31.39, 30.45, 32.61, 29.11),
                 Silicate = c (17.19643, 19.51786, 24.07143, 14.78571, 27.64286))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324295146&siteId=291194637