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 :
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.
