Search code examples
rggplot2data-visualizationvisualizationaxis-labels

R: Changing the color of secondary axis tick labels with ggplot


I am trying to produce secondary axis tick labels that are a different color from the primary tick labels in ggplot.

I have a plot containing two sets of lines and corresponding, different y-axes. As demonstrated in the minimal example below, I have successfully made each line + axis label pair share common colors that distinguish them from the other pair. However, I want the tick labels also to also share those colors.

The intuitive approach would be to use sec.axis and sec_axis, but they do not appear to provide a means to distinguish the formatting of the ticks/labels of the secondary axis from those of the primary axis.

Anyone have a way of changing the colors of secondary axis tick labels without changing those of the primary axis?

library(ggplot2)

# Example data
df <- data.frame(y1 = 1:10,
           y2 = 2:11,
           x = 101:110)

# Example plot
df %>% ggplot2::ggplot() +
  geom_line(
    mapping = aes(x = x, y = y1),
    color = "black") +
  geom_point(
    mapping = aes(x = x, y = y1),
    color = "black") +
  geom_line(
    mapping = aes(x = x, y = y2),
    color = "red") +
  geom_point(
    mapping = aes(x = x, y = y2),
    color = "red") +
  scale_y_continuous(
    "Primary",
    sec.axis = sec_axis(~ ., name = "Secondary")
  ) +
  theme_bw() +
  theme(
    axis.title.y = element_text(color = "black"),
    axis.title.y.right = element_text(color = "red")
)

Example Plot


Solution

  • Your code is fine, just add in theme():

    axis.text.y.right = element_text(colour = "red")
    

    Like this:

    df %>% ggplot2::ggplot() +
      geom_line(
        mapping = aes(x = x, y = y1),
        color = "black") +
      geom_point(
        mapping = aes(x = x, y = y1),
        color = "black") +
      geom_line(
        mapping = aes(x = x, y = y2),
        color = "red") +
      geom_point(
        mapping = aes(x = x, y = y2),
        color = "red") +
      scale_y_continuous(
        "Primary",
        sec.axis = sec_axis(~ ., name = "Secondary")
      ) +
      theme_bw() +
      theme(
        axis.title.y = element_text(color = "black"),
        axis.title.y.right = element_text(color = "red"),
        axis.text.y.right = element_text(colour = "red")) #ADD THIS
    

    Good luck!

    Color ticks