8
votes

For each tick label on the y axis, I would like to change: label -> 2^label

I am plotting log-log data (base 2), but I would like the labels to show the original data values.

I know I can get the current y labels with ylabels = plt.getp(plt.gca(), 'yticklabels')

This gives me a list: <a list of 9 Text yticklabel objects> each of which is a <matplotlib.text.Text object at 0x...>

I looked at the documentation of the text objects at http://matplotlib.org/users/text_props.html but I'm still not sure what the correct syntax is to change the string in each text label.

Once I change the labels, I could set them on the axis using:

plt.setp(plt.gca(), 'yticklabels', ylabels)

2
Did you use something like loglog(x, y, basex=2, basey=2)? When I do that, the labels are already in the form 2^k. - Warren Weckesser
@WarrenWeckesser no, it's actually on a box plot - Joe

2 Answers

11
votes

If you want to do this in a general case you can use FuncFormatter (see : matplotlib axis label format, imshow: labels as any arbitrary function of the image indices. Matplotlib set_major_formatter AttributeError)

In you case the following should work:

import matplotlib as mpl
import matplotlib.pyplot as plt

def mjrFormatter(x, pos):
    return "$2^{{{0}}}$".format(x)

def mjrFormatter_no_TeX(x, pos):
    return "2^{0}".format(x)

ax = plt.gca()
ax.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter))
plt.draw()

The absured {} escaping is a consequence of the new-style string frommating

-1
votes