Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In ggplot2, how to add secondary axis for descrete variable?

I want to add secondary axis in ggplot2, but scale_y_discrete(sec.axis = dup_axis()) can’t work.How to fix it ? Thanks!

library(tidyverse)
diamonds %>% group_by(cut,color) %>% summarise(max_x = max(x)) %>% 
  ggplot(aes(x= cut,y=color,fill=max_x)) + geom_tile()+
  scale_y_discrete(sec.axis = dup_axis())

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

At present ggplot2 does not support a secondary axis for discrete scales (but it will in the next (?) release. See here).

Instead one option would to use a continuous scale which however requires some additional work to set the breaks and labels:

library(tidyverse)

ybreaks <- seq_len(nlevels(diamonds$color))
ylabels <- levels(diamonds$color)

diamonds %>%
  group_by(cut, color) %>%
  summarise(max_x = max(x)) %>%
  mutate(color_num = as.numeric(color)) %>%
  ggplot(aes(x = cut, y = color_num, fill = max_x)) +
  geom_tile() +
  scale_y_continuous(
    breaks = ybreaks, labels = ylabels, sec.axis = dup_axis(),
    expand = expansion(mult = 0, add = .1)
  )
#> `summarise()` has grouped output by 'cut'. You can override using the `.groups`
#> argument.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading