简体   繁体   中英

Adding a custom tick and label

I would like to add a custom major tick and label in matplotlib. A typical use is to add a label at the location math.pi with the label "$\\pi$" . My aim is to leave the other ticks as is: I would like to retain the original major and minor ticks with the formatting that have been previously chosen but with this extra tick and label. I have figured out a way (and found posts on these forums) to add the tick:

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

My trouble is with the label. I have tried to retrieve the labels in a similar way with ax.xaxis.get_majorticklabels() but that gives me a list of matplotlib.text.Text which I am unsure how to deal with. My intention was to get the list of labels as strings, to add the new label (at the correct position) and then use ax.xaxis.set_ticklabels(list_label) in a way that is similar to the location.

This is what I usually do, though I've never been completely satisfied with the approach. There may be a better way, without calling 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()

在此处输入图片说明

I"m late to the party, but here's my solution, which preserves the original automatic tick location and formatting (or whatever Locator/Formatter you set on the axes), and simply adds new ticks. The solution also works when you move the view, ie when dragging or zooming in a GUI.

I basically implement a new Locator and a new Formatter that chain to original ones.

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)

These two can be used like any other Locator/Formatter directly, or with this little helper method

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

Example usage:

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$'
})

在此处输入图片说明

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