I have a figure with a log axis
and I would like to relabel the axis ticks with logs of the values, rather than the values themselves
The way I've accomplished this is with
plt.axes().set_xticklabels([math.log10(x) for x in plt.axes().get_xticks()])
but I wonder if there isn't a less convoluted way to do this.
What is the correct idiom for systematically relabeling ticks on matplotlib
plots with values computed from the original tick values?
To fix the position of ticks, use set_xticks() function. To set string labels at x-axis tick labels, use set_xticklabels() function.
Ticks are the markers denoting data points on the axes and tick labels are the name given to ticks. By default matplotlib itself marks the data points on the axes but it has also provided us with setting their own axes having ticks and tick labels of their choice.
Look into the Formatter
classes. Unless you are putting text on your ticks you should almost never directly use set_xticklabels
or set_yticklabels
. This completely de-couples your tick labels from you data. If you adjust the view limits, the tick labels will remain the same.
In your case, a formatter already exists for this:
fig, ax = plt.subplots()
ax.loglog(np.logspace(0, 5), np.logspace(0, 5)**2)
ax.xaxis.set_major_formatter(matplotlib.ticker.LogFormatterExponent())
matplotlib.ticker.LogFormatterExponent
doc
In general you can use FuncFormatter
. For an example of how to use FuncFomatter
see matplotlib: change yaxis tick labels which one of many examples floating around SO.
A concise example for what you want, lifting exactly from JoeKington in the comments,:
ax.xaxis.set_major_formatter(
FuncFormatter(lambda x, pos: '{:0.1f}'.format(log10(x))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With