1

Using the example data below and the respective plot, I simply want to add text for each of the three cyl groups at the top, e.g. for cyl = 4, I want to add a label like "abc", for cyl = 6 a label like "xyz" and so on.

I know that ggplot doesn't like secondary axes, and in my case I don't even want to display additional data, I just want to add second/alternative axis labels.

library(tidyverse)
mtcars |>
  mutate(cyl = as.character(cyl)) |>
  ggplot() +
  geom_tile(aes(x = cyl, y = gear, fill = disp))

This is what I have:

enter image description here

This is what I want:

enter image description here

Any ideas?

8
  • sec_axis takes many of the same arguments as scale_x_continuous, including breaks= and labels=. Just provide an "identity" transform (~ .) and provide both arguments, as in ... + scale_x_continuous(sec.axis = sec_axis(~ ., breaks = c(4, 6, 8), labels = c("abc", "def", "ghi"))) Commented Oct 24, 2023 at 13:26
  • If my comment and the dupe-links don't give you what you need, @-ping me and let me know what's incomplete. Thanks! Commented Oct 24, 2023 at 13:29
  • Thanks @r2evans. Seems my example wasn't appropriate enough. When the x axis is continuous (like in teh example), your approach works. However, let's assume, the original x axis doens't have numeric values like 4, 6, 8, but instead factor or character values like "A", "B", "C". Commented Oct 24, 2023 at 13:43
  • I updated my example accordingly. Commented Oct 24, 2023 at 13:45
  • 1
    Thanks @r2evans. Looking at github, this workaround does the trick in my case: github.com/tidyverse/ggplot2/issues/3171#issuecomment-614084750 Commented Oct 24, 2023 at 13:56

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.