8

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)

Joe
  • 903
  • 3
  • 11
  • 20

2 Answers2

11

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

Community
  • 1
  • 1
tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • Running this, I get warnings that I don't know how to interpret: – Joe Feb 28 '13 at 21:19
  • /usr/lib/python2.7/site-packages/matplotlib/font_manager.py:1242: UserWarning: findfont: Font family ['STIXSizeOneSym'] not found. Falling back to Bitstream Vera Sans (prop.get_family(), self.defaultFamily[fontext])) – Joe Feb 28 '13 at 21:20
  • /usr/lib/python2.7/site-packages/matplotlib/font_manager.py:1252: UserWarning: findfont: Could not match :family=Bitstream Vera Sans:style=normal:variant=normal:weight=normal:stretch=normal:size=12. Returning /usr/share/fonts/thai-scalable/Waree-Oblique.ttf UserWarning) /usr/lib/python2.7/site-packages/matplotlib/font_manager.py:1242: UserWarning: findfont: Font family ['STIXSizeThreeSym'] not found. Falling back to Bitstream Vera Sans (prop.get_family(), self.defaultFamily[fontext])) – Joe Feb 28 '13 at 21:20
  • It looks like you are having issue with `TeX`. See edit for non-TeX version. You should open a new question if you can't get those sorted out. – tacaswell Feb 28 '13 at 21:55
-1

As per http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_yticks

a = plt.gca()
a. set_yticks(list_of_labels)

Parker
  • 8,539
  • 10
  • 69
  • 98
  • 1
    using `set_yticks` is dangerous, because it decouples the tick labels from your data. The text of the tick label is fixed, but the location of the ticks can change. – tacaswell Aug 16 '13 at 16:19