Closed
Description
While building a derivative of facet_wrap
, I stacked several plots, produced from mtcars
data set, and noticed, that, with sec.axis
set, top axis ticks of the bottom plot do not exactly align with the bottom ticks of the top plot. (See figures below).
And a zoomed-in version.
The issue does not seem to be related to any of my modifications and can be easily reproduced in base ggplot2
.
In the reprex I build a simple plot with a secondary x axis, then check grobs of each axis and retrieve the x
coord of polyLine
grob. The difference, while small, is clearly seen.
library(ggplot2, quietly = TRUE, warn.conflicts = FALSE)
library(dplyr, quietly = TRUE, warn.conflicts = FALSE)
library(grid, quietly = TRUE, warn.conflicts = FALSE)
# Simple plot with secondary, duplicated, x-axis
ggplot(mtcars, aes(hp, mpg)) +
geom_point() +
scale_x_continuous(sec.axis = dup_axis()) -> plt
# Converting to gtable to get each grob
plt %>% ggplot_build %>% ggplot_gtable -> tbl
tbl$layout %>% mutate(rowid = 1:n()) -> layout
# Indices of grobs
top_ind <- layout %>% filter(name == "axis-t") %>% pull(rowid)
bot_ind <- layout %>% filter(name == "axis-b") %>% pull(rowid)
# Axis grob is nested, so go deep until we hit the `polyLine` and its `x` coordinates
tbl$grobs[[top_ind]]$children[[2]]$grobs[[2]]$x -> top_tick_pos
# For another axis, slightly different order
tbl$grobs[[bot_ind]]$children[[2]]$grobs[[1]]$x -> bot_tick_pos
# Compare
print(top_tick_pos)
#> [1] 0.199199199199199native 0.199199199199199native 0.52052052052052native
#> [4] 0.52052052052052native 0.841841841841842native 0.841841841841842native
print(bot_tick_pos)
#> [1] 0.199646643109541native 0.199646643109541native 0.520880179890781native
#> [4] 0.520880179890781native 0.842113716672021native 0.842113716672021native
diff <- convertX(bot_tick_pos, "native", TRUE) - convertX(top_tick_pos, "native", TRUE)
avg_diff <- sqrt(sum(diff^2) / length(diff))
print(avg_diff)
#> [1] 0.0003667319
Created on 2019-10-18 by the reprex package (v0.3.0)
This is reproduced in 115c396.
Metadata
Metadata
Assignees
Labels
No labels