簡體   English   中英

使用matplotlib.ticker設置Matplotlib Ytick標簽會產生關鍵錯誤

[英]Setting Matplotlib Ytick labels with matplotlib.ticker yields key error

我想設置y-ticker標簽,但仍將它們綁定到數據。 通過這個問題, matplotlib:更改yaxis刻度標簽 ,我正在嘗試使用matplotlib.ticker做到這一點。

我目前只想在三個位置上打勾: [.25, .5, .75] 該圖可以正確生成,但是使用print語句,我可以看到它遍歷每個標簽兩次以及字典中沒有的其他一些隨機值,從而在此行上生成了關鍵錯誤: return label_lookup[x] 這些值似乎與每次運行的值都不相同。 是什么導致此問題?

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()

我本人不是matplotlib的專家,但是您似乎想使用FixedFormatter而不是FuncFormatter。 FixedFormatter僅采用一系列字符串而不是函數,並發出適當的標簽。 通過使用FixedFormatter,您只需要3個標簽,而對於FuncFormatter,則必須具有所有傳入的x的有效值。

只需更換

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

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

而沒有KeyErrors,您將獲得相同的結果。 然后,您也可以擺脫mjrFormatter ,因為您不再使用它。

另外,如果您確實想使用FuncFormatter,則必須能夠接受任何x,而不僅僅是精確的0.25、0.5和0.75。 您可以按以下方式重寫mjrFormatter

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

您的字典label_lookup並不使我成為理想的工作方式。 您可以盡力使它工作,但是字典的無序性質使其很難擁有簡單的不等式檢查鏈,這就是為什么我對值進行硬編碼的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM