Skip to main content

plotting - Aligning plot axes in a graphics object


I need to align the y-axes in the plots below. I think I'm going to have to do some rasterizing and searching for vertical lines, then vary x and w. Is there a better way?



a = ListPlot[{{0, 0}, {16, 20}},
PlotRange -> {{0, 16}, {0, 20}}, Frame -> True];
b = ListPlot[{{0, 0}, {160000, 200000}},
PlotRange -> {{0, 160000}, {0, 200000}}, Frame -> True];
x = 3.1; w = 5;
Graphics[{LightYellow, Rectangle[{0, 0}, {7, 8}],
Inset[a, {x, 5.5}, Center, {w, Automatic}],
Inset[b, {3.1, 2.2}, Center, {5, Automatic}]},
PlotRange -> {{0, 7}, {0, 8}}, ImageSize -> 300]


enter image description here



Answer



This is a common (and very big) annoyance when creating graphics with subfigures. The most general (but somewhat tedious) solution is setting an explicit ImagePadding:


GraphicsColumn[
{Show[a, ImagePadding -> {{40, 10}, {Automatic, Automatic}}],
Show[b, ImagePadding -> {{40, 10}, {Automatic, Automatic}}]}]

Mathematica graphics


This is tedious because you need to come up with values manually. There are hacks to retrieve the ImagePadding that is used by the Automatic setting. I asked a question about this before. Using Heike's solution from there, we can try to automate the process:


padding[g_Graphics] := 

With[{im = Image[Show[g, LabelStyle -> White, Background -> White]]},
BorderDimensions[im]]

ip = 1 + Max /@ Transpose[{First@padding[a], First@padding[b]}]

GraphicsColumn[
Show[#, ImagePadding -> {ip, {Automatic, Automatic}}] & /@ {a, b}]

The padding detection that's based on rasterizing might be off by a pixel, so I added 1 for safety.


Warning: the automatic padding depends on the image size! The tick marks or labels might "hang out" a bit. You might need to use padding@Show[a, ImageSize -> 100] to get something that'll work for smaller sizes too.



I have used this method myself several times, and while it's a bit tedious at times, it works well (much better than figuring out the image padding manually).


Comments