Is it possible to add a third y-axis to ggplot2?

Viewed 352

Is there a possibility to add a third y-axis to a plot with ggplot2? I have three different datasources I want to display in the plot. I already added a second y-axis, for the next dataset the scale is again very different, why I'm looking now for a solution.

So far I only found how to add a second axis, for example as shown [here].(https://r-graph-gallery.com/line-chart-dual-Y-axis-ggplot2.html) But I whether there is an possibility to add another one... Thank you!

2 Answers

This is equally clunky, but shows how it can be done from scratch using only CRAN resources.

library(cowplot)
library(patchwork)

p1 <- ggplot(df, aes(Sepal.Width, Sepal.Length)) + 
                   geom_point() + theme(axis.line = element_line())
p2 <- ggplot(df, aes(Sepal.Width, Petal.Width)) + geom_point() +
                   theme(axis.line = element_line())

p3 <- ggplot(df, aes(Sepal.Width, Petal.Length)) + 
  geom_point(aes(color = "Petal.Length")) +
  geom_point(aes(y = Sepal.Length/100, color = "Sepal.Length")) +
  geom_point(aes(y = Petal.Width / 1000, color = "Petal.Width")) +
  theme(axis.line = element_line(),
        plot.margin = margin(10, 10, 10, 30))

wrap_elements(get_plot_component(p1, "ylab-l")) +
  wrap_elements(get_y_axis(p1)) +
  wrap_elements(get_plot_component(p2, "ylab-l")) +
  wrap_elements(get_y_axis(p2)) +
  p3 + 
  plot_layout(widths = c(3, 1, 3, 1, 40))

enter image description here


Data used

df <- iris
df$Sepal.Length <- df$Sepal.Length * 100
df$Petal.Width <- df$Petal.Width * 1000

This is a very clunky solution based on extracting elements from previously plotted graphs and editing grid objects. It may or not give you a workable solution.

source("https://raw.githubusercontent.com/davidearn/plague_growth/master/analysis/plots/3axes.R")
set.seed(101)
dd <- data.frame(x=rnorm(20),y=rnorm(20))
library(ggplot2)
gg0 <- ggplot(dd)
g1A <- gg0 + geom_point(aes(x,y))
g1B <- gg0 + geom_point(aes(x,10*y))
g1C <- gg0 + geom_point(aes(x,100*y))
## use return_gtable = TRUE if planning to add further axes
g2 <- combine_axes(g1A,g1B,add_pos="l", return_gtable=TRUE)
g3 <- combine_axes(g2,g1C,add_pos="l")
print(g3)

ugly graph with triple left axes

Related