tchakravarty tchakravarty - 3 months ago 13
R Question

R: Dual y-axis panel.grid.major not aligning

I am trying to follow the instructions here on how to create a dual y-axis plot (yes, I know). My code is here.

However, in the output some of the major grid lines are slightly misaligned (see the red box), whereas some of them are perfectly aligned. I am not sure what is causing this dilation of one of the plots. I rewrote the code on that site to understand it better and have possibly introduced a bug somewhere.

enter image description here

An easy fix would be to turn off grid lines on one of the plots, but that seems to be hiding the problem rather than fixing it.




Edit:



I tried running the original code here unchanged, and I ran into the following error on line 130.

> ticks$grobs[[1]]$x <- ticks$grobs[[1]]$x - unit(1, "npc") + tml
Error in Ops.unit(ticks$grobs[[1]]$x, unit(1, "npc")) :
both operands must be units


So, I cannot check if the issue is a bug that I have introduced while transcription.

Answer

Your code in the gist doesn't run (and it's also a bit complicated).

To understand why the lines aren't aligned, consider this example:

  • axis1: range: 0 - 1. The value of 0.5 is mid-way between 0 and 1.
  • axis2: range: 0 - 10. The value of 5 is mid-way between 0 and 10.

Now in your graph you have (something like)

  • axis1: range: 0 - 1.1. The value of 0.5 is 0.5/1.1 = 0.45 between 0 and 1.
  • axis2: range: 0 - 10.1. The value of 5 is 5/10.1 = 0.495 between 0 and 10.
  • Result: mis-aligned lines.

You shouldn't add a constant to each axis, the value needs to be proportional to the scale.

Comments