Description
When converting a plot with secondary axis transformation from Cartesian to polar coordinates, I noticed two issues:
-
Label positions for the secondary axis become mis-aligned to match those of the primary axis;
-
When the secondary axis had fewer labels than the primary axis, the secondary axis label values are recycled to fill all the positions used by primary axis labels.
Reprex with annotated plots below:
library(ggplot2)
p <- ggplot(data.frame(x = LETTERS[1:3],
y = c(19, 22, 14)),
aes(x, y)) +
geom_col() +
scale_y_continuous(
name = "miles per gallon",
sec.axis = sec_axis(name = "km per litre",
trans = ~. * 0.425))
cowplot::plot_grid(
p + ggtitle("Correct labels"),
p + ggtitle("Wrong labels") +
coord_polar(),
ncol = 2)
I suspect this is caused by the render_axis_v
function in CoordPolar
, more specifically the following section, which sets the axis label positions of the secondary axis to match those of the primary axis:
x <- r_rescale(self, panel_params$r.major, panel_params) + 0.5
panel_params$r.major <- x
if (!is.null(panel_params$r.sec.major)) {
panel_params$r.sec.major <- x
}
I was able to get the expected result when I modified the function to replace panel_params$r.sec.major <- x
with the following line (essentially repeating the calculation done in r_rescale
for secondary axis breaks & range):
panel_params$r.sec.major <- scales::rescale(panel_params$r.sec.major,
c(0, 0.4),
panel_params$r.sec.range) + 0.5