teunbrand / ggh4x

ggplot extension: options for tailored facets, multiple colourscales and miscellaneous
https://teunbrand.github.io/ggh4x/
Other
542 stars 33 forks source link

guide_axis_minor: non-default minor tick positions don't work with sec_axis() #28

Closed ndp32 closed 3 years ago

ndp32 commented 3 years ago

Hi Teunbrand,

{ggh4x} is great, thank you for developing it.

I found what looks like a bug in guide_axis_minor. When I tried to create a plot with minor tick marks on each side of the plot using sec.axis = dup_axis() in the scale_(x|y)_continuous functions I found that setting custom minor tick marks did not work for the duplicate axes. The code below should demonstrate the issue.

ggplot(mtcars, aes(wt, mpg)) + geom_point() + scale_x_continuous( minor_breaks = seq(2, 4, by = 0.2), guide = "axis_minor", sec.axis = dup_axis() )

I have been trying to track down the reason for this behavior but have yet to find it (I am not the ggproto/guide system ninja that you are. Do you have any idea how to fix this problem, or point me in the direction of a solution?

Thanks again for making this package, it is both useful and instructive.

Best, Niko

teunbrand commented 3 years ago

Hi Niko,

Thanks for reporting this, I hadn't anticipated myself that something like this would happen. As far as I can see, there is something going awry in constructing the view scale of the secondary axis, wherein minor break info is not derived from the primary axis but instead recalculated. I'm relatively sure this is true for other secondary axis specifications too, besides dup_axis(). I don't think vanilla ggplot2 uses the minor breaks of secondary axes anywhere, so it might not be worth the trouble for them to fix this.

As a workaround for dup_axis(), I'd suggest the following:

library(ggplot2)
library(ggh4x)

ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  scale_x_continuous(minor_breaks = seq(2, 4, by = 0.2),
                     guide = "axis_minor") +
  guides(x.sec = guide_axis_minor(title = "wt"))

Created on 2020-10-28 by the reprex package (v0.3.0)

Best, Teun

ndp32 commented 3 years ago

Thanks for the quick response.

Your insight about the viewscale recalculating the minor break info does seem to be the cause of the problem.

I did not realize that you could specify the secondary axis with guides() as you did above. That workaround is sufficient for my purposes.

Thanks again for the help.