簡體   English   中英

添加自定義刻度和標簽

[英]Adding a custom tick and label

我想在 matplotlib 中添加一個自定義的主要刻度和標簽。 一個典型的用途是在math.pi位置添加一個標簽,標簽為"$\\pi$" 我的目標是保持其他刻度不變:我想保留原始的主要和次要刻度以及先前選擇的格式,但帶有這個額外的刻度和標簽。 我想出了一種方法(並在這些論壇上找到了帖子)來添加勾號:

list_loc=list(ax.xaxis.get_majorticklocs())
list_loc.append(pos)
list_loc.sort()
ax.xaxis.set_ticks(list_loc)

我的問題是標簽。 我試圖用ax.xaxis.get_majorticklabels()以類似的方式檢索標簽,但這給了我一個matplotlib.text.Text的列表,我不確定如何處理。 我的目的是將標簽列表作為字符串獲取,添加新標簽(在正確的位置),然后以類似於位置的方式使用ax.xaxis.set_ticklabels(list_label)

這是我通常所做的,盡管我從未完全滿意此方法。 沒有調用draw()可能會有更好的方法。

fig,ax=plt.subplots()
x=linspace(0,10,1000)
x.plot(x,exp(-(x-pi)**2))
plt.draw() # this is required, or the ticklabels may not exist (yet) at the next step
labels = [w.get_text() for w in ax.get_xticklabels()]
locs=list(ax.get_xticks())
labels+=[r'$\pi$']
locs+=[pi]
ax.set_xticklabels(labels)
ax.set_xticks(locs)
ax.grid()
plt.draw()

在此處輸入圖片說明

我遲到了,但這是我的解決方案,它保留了原始的自動刻度位置和格式(或您在軸上設置的任何定位器/格式器),並且只需添加新刻度。該解決方案在您移動視圖時也有效, 即在 GUI 中拖動或放大時。

我基本上實現了一個新的定位器和一個鏈接到原始定位器的新格式器。

import matplotlib.ticker as mticker
class AdditionalTickLocator(mticker.Locator):
    '''This locator chains whatever locator given to it, and then add addition custom ticks to the result'''
    def __init__(self, chain: mticker.Locator, ticks) -> None:
        super().__init__()
        assert chain is not None
        self._chain = chain
        self._additional_ticks = np.asarray(list(ticks))

    def _add_locs(self, locs):
        locs = np.unique(np.concatenate([
            np.asarray(locs),
            self._additional_ticks
        ]))
        return locs

    def tick_values(self, vmin, vmax):
        locs = self._chain.tick_values(vmin, vmax)
        return self._add_locs(locs)

    def __call__(self):
        # this will call into chain's own tick_values,
        # so we also add ours here
        locs = self._chain.__call__()
        return self._add_locs(locs)

    def nonsingular(self, v0, v1):
        return self._chain.nonsingular(v0, v1)
    def set_params(self, **kwargs):
        return self._chain.set_params(**kwargs)
    def view_limits(self, vmin, vmax):
        return self._chain.view_limits(vmin, vmax)


class AdditionalTickFormatter(mticker.Formatter):
    '''This formatter chains whatever formatter given to it, and
    then does special formatting for those passed in custom ticks'''
    def __init__(self, chain: mticker.Formatter, ticks) -> None:
        super().__init__()
        assert chain is not None
        self._chain = chain
        self._additional_ticks = ticks

    def __call__(self, x, pos=None):
        if x in self._additional_ticks:
            return self._additional_ticks[x]
        res = self._chain.__call__(x, pos)
        return res

    def format_data_short(self, value):
        if value in self._additional_ticks:
            return self.__call__(value)
        return self._chain.format_data_short(value)

    def get_offset(self):
        return self._chain.get_offset()
    
    def _set_locator(self, locator):
        self._chain._set_locator(locator)

    def set_locs(self, locs):
        self._chain.set_locs(locs)

這兩個可以像任何其他定位器/格式化程序一樣直接使用,或者使用這個小助手方法

def axis_add_custom_ticks(axis, ticks):
    locator = axis.get_major_locator()
    formatter = axis.get_major_formatter()
    axis.set_major_locator(AdditionalTickLocator(locator, ticks.keys()))
    axis.set_major_formatter(AdditionalTickFormatter(formatter, ticks))

用法示例:

fig, ax = plt.subplots()
x = np.linspace(0,10,1000)
ax.plot(x,np.exp(-(x-np.pi)**2))

axis_add_custom_ticks(ax.xaxis, {
    np.pi: '$\pi$'
})

在此處輸入圖片說明

暫無
暫無

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

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