rggplot2

Pass data object inside the secondary axis


I have below ggplot

library(ggplot2)
ggplot(faithfuld, aes(waiting, eruptions, z = density)) +
    geom_raster(aes(fill = density)) +
    geom_contour(colour = "white", binwidth = 0.002) +    
    scale_y_continuous(expand = c(0,0), n.breaks = 7, sec.axis = sec_axis(transform = ~ round(., 5), name = "eruptions", breaks = seq(min(eruptions),max(eruptions),length.out = 9))) +
    theme(axis.text.y.left = element_blank(), axis.ticks.y.left = element_blank(), axis.title.y.left = element_blank())

Above code fails to generate any plot because due to seq(min(eruptions),max(eruptions),length.out = 9)

How can I pass data inside the secondary axis without explicitly define outside of the ggplot chain?

Appreciate your pointer.


Solution

  • I don't think breaks= can take a ~-programmatic entry the way that they do for other elements. You can use with(faithfuld, ...) inline:

    data("faithfuld", package="ggplot2")
    ggplot(faithfuld, aes(waiting, eruptions, z = density)) +
        geom_raster(aes(fill = density)) +
        geom_contour(colour = "white", binwidth = 0.002) +    
        scale_y_continuous(
          expand = c(0,0), n.breaks = 7,
          sec.axis = sec_axis(
            transform = ~ round(., 5), name = "eruptions",
            breaks = with(faithfuld, seq(min(eruptions), max(eruptions), length.out = 9)) )
        ) +
        theme(axis.text.y.left = element_blank(), axis.ticks.y.left = element_blank(), axis.title.y.left = element_blank())
    

    ggplot image with the secondary axis breaks filled correctly

    However ... with what you're doing, it seems easier to work with the primary axis and move it to the right by using position="right" instead of a secondary axis:

    ggplot(faithfuld, aes(waiting, eruptions, z = density)) +
        geom_raster(aes(fill = density)) +
        geom_contour(colour = "white", binwidth = 0.002) +    
        scale_y_continuous(
          expand = c(0,0), n.breaks = 7, position = "right"
        )
    

    same data and plot, putting the primary axis/labels on the right directly instead of using sec_axis()