简体   繁体   中英

Setting Matplotlib Ytick labels with matplotlib.ticker yields key error

I would like to set y-ticker labels, but still have them bound to the data. Via this question, matplotlib: change yaxis tick labels , I am trying to do this with matplotlib.ticker .

I currently just want tick marks at three positions: [.25, .5, .75] . The graph generates correctly, but with the print statements, I can see it iterates over each label twice and some other random values that are not in my dictionary and thus generate key errors on this line: return label_lookup[x] . The values do not appear to be the same it's run each time. What is causing this issue?

import matplotlib as mpl
import matplotlib.pyplot as plt

label_lookup = {.25: 'Label 1',
                .5: 'Label 2',
                .75: 'Label 3'}

def mjrFormatter(x, pos):
    print x, pos
    return label_lookup[x]

ax = plt.gca()
ax.set_yticks([.25,.5,.75], minor=False)
ax.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter))
plt.draw()
plt.show()

I'm not an expert at matplotlib myself, but it looks like you want to be using a FixedFormatter instead of a FuncFormatter. The FixedFormatter just takes a sequence of strings instead of a function, and emits the appropriate label. By using a FixedFormatter, you only need your 3 labels, while with a FuncFormatter, you have to have valid values for all x's passed in.

Simply replace

ax.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter))

with

ax.yaxis.set_major_formatter(mpl.ticker.FixedFormatter(['Label 1', 'Label 2', 'Label 3']))

and you'll get the same results without the KeyErrors. You can also then get rid of mjrFormatter , since you're no longer using it.

Alternatively, if you really want to use FuncFormatter, you have to be able to accept any x, not just the exact values of 0.25, 0.5, and 0.75. You could rewrite mjrFormatter as follows:

def mjrFormatter(x, pos):
    print x, pos
    if x <= .25:
         return 'Label 1'
    if x <= .5:
         return 'Label 2'
    return 'Label 3'

Your dictionary label_lookup doesn't strike me as the ideal way to do things. You could make it work with enough effort, but the unordered nature of the dictionary makes it hard to have a simple chain of inequality checks, which is why I hardcoded the values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM