'Formatting axis in ggplot to show two datasets

I have a figure with two y-axis and three geoms.

I have used sec.axis function to add the second y-axis but that leaves two geoms that I want to represent on one y axis. The range 1-100 works for both geoms so that’s fine, but the units are different, so I’d like a way of splitting up the titles so that they visually look different. Is there a way of getting the y axis description onto two lines or adding other formatting?



Solution 1:[1]

Using the {ggtext} package, you can colour-code (parts of) your y-axes in sync with the geom colours.

library(ggplot2)
library(ggtext)

df <- data.frame(
  x = 1:10,
  weight = runif(10, 0, 100),
  volume = runif(10, 0, 100),
  length = runif(10, -100, 0)
)

add <- 100

ggplot(df, aes(x)) +
  geom_point(aes(y = weight, colour = "weight")) +
  geom_point(aes(y = volume, colour = "volume")) +
  geom_point(aes(y = length + add, colour = "length")) +
  scale_colour_manual(values = c("red", "green", "blue")) +
  scale_y_continuous(
    name = "<span style='color:green'>volume [L]</span> / <span style='color:blue'>weight [kg]</span>",
    sec.axis = sec_axis(~ .x - add, name = "length [m]")
  ) +
  theme(
    axis.title.y.left = element_markdown(),
    axis.title.y.right = element_text(colour = "red")
  )

Created on 2022-02-17 by the reprex package (v2.0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 teunbrand