Creating nice-looking plots in Python is easy with matplotlib. Here’s an example of plotting some data as a histogram.
I like that looking at a matplotlib script is reasonably self-explanatory. Most of the default values are sensible, so it doesn’t take much to create something that looks alright. The above code produces the following.
The only interesting configuration we do is to slightly shrink the figure size, shift the x and y labels to the right of their respective axes, and to tighten up the figure margins. All of these are just cosmetic changes to bring the look inline with what I’m used to.
The problem comes when the axis tick values are large enough to warrant an exponent or offset.
If we change
sigma to some large values, we can see the problem.
This shifts the mean of the distribution to ten million, and changes to width to one million. Running the code above with this change, we get the following.
The problem is that the exponential prefix is covered by the axis label.
(This prefix is equivalent to scientific notation, where numbers like
1230 are represented as
1.230e3, read as ‘one point two three zero times ten to the power three’.)
I came across this while creating a scipt to convert ROOT canvases to matplotlib figures (available soon!).
Googling didn’t help, so I ended up looking throught the matplotlib source code.
To access the
Text object that holds the exponential label, one uses
ax is the Axes instance.
Once you have this, you can manipulate the object’s size, position, colour, and a bunch of other properties.
To shift the exponential label (called ‘offset text’ in matplotlib jargon, as it can also hold an offset value), you can do
x property is the x-position of the
Text object, from 0 to 1 left-to-right.)
Making this modification, the plot now looks like this.
Much better! But it stills look odd. It’s more conventional to have the exponential label on the right. So, let’s shift the axis label slightly to the left, and keep the exponential fully to the right.
Now we’re pretty much there.
Nice. My only problem with this result is that the offset text is sitting on a slightly higher baseline than the axis label. This happens because the offset text is actually part of the axis, whereas the label is not. This also means its y-position can’t be modified.
If this really bugs you, you can append the offset text to the axis label and hide the offset text itself. You need to draw the figure first in order for the text to be created.
All these changes gives the following.
The full code for this final figure is available as a gist.
This solution isn’t ideal, it could look better and be implemented more elegantly, but it’s not a bad start.