rggplot2axis

How to make "axis_logticks" work on secondary axes with ggplot2 in R?


I'd like to show log tick marks on both primary and secondary axes in a log-log plot using ggplot2.
R version: 4.4.2
ggplot2 version: 3.5.2

Here's a simple log-log plot:

library(ggplot2)

ggplot() +
    scale_x_log10(limits=c(10^0, 10^4),
        sec.axis=dup_axis()) +
    scale_y_log10(limits=c(10^-4, 10^0),
        sec.axis=dup_axis()) +
    geom_function(fun=function(x) 1/x)

When I add "axis_logticks" as a guide, it fails with the following message:

ggplot() +
    scale_x_log10(limits=c(10^0, 10^4), guide="axis_logticks",
                  sec.axis=dup_axis()) +
    scale_y_log10(limits=c(10^-4, 10^0), guide="axis_logticks",
                  sec.axis=dup_axis()) +
    geom_function(fun=function(x) 1/x)
Error in seq.default(start, end, by = 1) : 'to' must be a finite number

Setting the guides separately works for the primary x- and y-axes:

ggplot() +
    scale_x_log10(limits=c(10^0, 10^4),
        sec.axis=dup_axis()) +
    scale_y_log10(limits=c(10^-4, 10^0),
        sec.axis=dup_axis()) +
    guides(x="axis_logticks", y="axis_logticks") +
    geom_function(fun=function(x) 1/x)

However, it fails again with the secondary x-axis, giving the same error message:

ggplot() +
    scale_x_log10(limits=c(10^0, 10^4),
        sec.axis=dup_axis()) +
    scale_y_log10(limits=c(10^-4, 10^0),
        sec.axis=dup_axis()) +
    guides(x="axis_logticks", y="axis_logticks",
           x.sec="axis_logticks") +
    geom_function(fun=function(x) 1/x)

Interestingly enough, with the secondary y-axis, it doesn't throw an error, but the secondary y-axis only partially has logticks:

ggplot() +
    scale_x_log10(limits=c(10^0, 10^4),
        sec.axis=dup_axis()) +
    scale_y_log10(limits=c(10^-4, 10^0),
        sec.axis=dup_axis()) +
    guides(x="axis_logticks", y="axis_logticks",
           y.sec="axis_logticks") +
    geom_function(fun=function(x) 1/x)

Solution

  • For me, + annotation_logticks(sides = "trbl") works, if ok to have the ticks on the inside.

    enter image description here

    Or annotation_logticks(sides = "trbl", outside = TRUE ) + coord_cartesian(clip = "off") gets them outside, but then we'll need to push the labels outward...

    enter image description here

    ...like with:

    theme(axis.text.y.left = element_text(margin = margin(r = 10)),
          axis.text.x.top = element_text(margin = margin(b = 10)),
          axis.text.y.right = element_text(margin = margin(l = 10)),
          axis.text.x.bottom = element_text(margin = margin(t = 10)))
    

    enter image description here