Home > Software design >  Is it possible to add a third y-axis to ggplot2?
Is it possible to add a third y-axis to ggplot2?

Time:03-27

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].(ugly graph with triple left axes

CodePudding user response:

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
  • Related