Duplicating (and modifying) discrete axis in ggplot2

前端 未结 1 1256
庸人自扰
庸人自扰 2020-11-30 10:55

I want to duplicate the left-side Y-axis on a ggplot2 plot onto the right side, and then change the tick labels for a discrete (categorical) axis.

I\'ve read the ans

相关标签:
1条回答
  • 2020-11-30 11:41

    Take your discrete factor and represent it numerically. Then you can mirror it and relabel the ticks to be the factor levels instead of numbers.

    library(ggplot2)
    
    irislabs1 <- levels(iris$Species)
    irislabs2 <- c("foo", "bar", "buzz")
    
    ggplot(iris, aes(Sepal.Length, as.numeric(Species))) +
      geom_point() +
      scale_y_continuous(breaks = 1:length(irislabs1),
                         labels = irislabs1,
                         sec.axis = sec_axis(~.,
                                             breaks = 1:length(irislabs2),
                                             labels = irislabs2))
    

    Then fiddle with the expand = argument in the scale as needed to more closely imitate the default discrete scale.

    0 讨论(0)
提交回复
热议问题