Short background: I'm trying to create a custom axis for a plot in R, where the axis labels are numeric but do not correspond to the coordinate values they are placed at. I want R to format the labels in scientific notation because right now they're coming out like "10000000" which is not ideal.
Long background: I am making multi-panel figures where each panel is a filled contour plot. The filled.contour
function will not make multi-panel figures, so I am using .filled.contour
, which eliminates the legend - so I have been making legends manually. I use rect
to create a stack of rectangles covering the color palette and axis
to label values on the legend. However, the labels on the legend are based on the z-values, not the y-values, so I have an axis with numeric labels that don't match the coordinates the labels are placed at. When I feed those numeric values to axis
manually, it stubbornly formats them NOT in scientific notation, which is suboptimal when the values are in the tens of millions.
This is the code as it's currently written:
breaks <- pretty(limits, n = 6)
marks <- (breaks - limits[1])/(limits[2] - limits[1]) # y-values in plot region go from 0 to 1
axis(side = 4, at = marks, labels = breaks, las = 1, tick = T, pos = 1.21, yaxs = "i", cex.axis = cex_legend, tcl = tickle)
Previously, I just adjusted the y-values of the contour plot to span the range of z-values (limits
), so that the at
and labels
arguments matched:
axis(side = 4, at = pretty(limits, n = 6), labels = T, las = 1, tick = T, pos = 1.21, yaxs = "i", cex.axis = cex_legend, tcl = tickle)
and when I did this the labels were nicely formatted in scientific notation. (I would have had the same problem with unformatted labels on the actual y-axis, since the labels and coordinates didn't match, but since the values on the y-axis just go from 0 to 1, their formatting isn't an issue.) For reasons I won't go into, it is now preferable to use the 'real' y-values for the contour plot, but this leads to unformatted labels on the axis for the color legend.
If I was just making a few plots I could create the labels manually, but I am making tons of these figures with all different legends so I need to be able to automate it.