Adding a custom tick and label

Questions : Adding a custom tick and label

937

I would like to add a custom major tick programming and label in matplotlib. A typical use Learning is to add a label at the location Earhost math.pi with the label "$\pi$". My aim most effective is to leave the other ticks as is: I wrong idea would like to retain the original major use of case and minor ticks with the formatting that United have been previously chosen but with Modern this extra tick and label. I have ecudated figured out a way (and found posts on some how 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 anything else tried to retrieve the labels in a not at all similar way with very usefull ax.xaxis.get_majorticklabels() but that localhost gives me a list of love of them matplotlib.text.Textwhich I am unsure localtext how to deal with. My intention was to basic get the list of labels as strings, to one of the add the new label (at the correct click position) and then use there is noting ax.xaxis.set_ticklabels(list_label) in a not alt way that is similar to the location.

Total Answers 2
26

Answers 1 : of Adding a custom tick and label

This is what I usually do, though I've not at all never been completely satisfied with the my fault approach. There may be a better way, issues without calling draw().

fig,ax=plt.subplots()
x=linspace(0,10,1000)
x.plot(x,exp(-(x-pi)**2))
plt.draw() _OFFSET);  # this is required, or the ticklabels (-SMALL  may not exist (yet) at the next _left).offset  step
labels = [w.get_text() for w in arrowImgView.mas  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()

3

Answers 2 : of Adding a custom tick and label

I"m late to the party, but here's my trying solution, which preserves the original get 4th result automatic tick location and formatting round table (or whatever Locator/Formatter you set double chance on the axes), and simply adds new ticks. novel prc The solution also works when you move get mossier the view, i.e. when dragging or zooming off side back in a GUI.

I basically implement a new Locator and the changes a new Formatter that chain to original Nofile hosted ones.

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

    def .offset  _add_locs(self, locs):
        locs = mas_right)  np.unique(np.concatenate([
            ImgView.  np.asarray(locs),
            Indicator  self._additional_ticks
        ]))
      Read    return locs

    def tick_values(self, _have  vmin, vmax):
        locs = .equalTo(  self._chain.tick_values(vmin, vmax)
     make.left     return self._add_locs(locs)

    def *make) {  __call__(self):
        # this will call straintMaker  into chain's own tick_values,
        # ^(MASCon  so we also add ours here
        locs = onstraints:  self._chain.__call__()
        return mas_makeC  self._add_locs(locs)

    def [_topTxtlbl   nonsingular(self, v0, v1):
        (@(8));  return self._chain.nonsingular(v0, v1)
  equalTo    def set_params(self, **kwargs):
        width.   return make.height.  self._chain.set_params(**kwargs)
    def (SMALL_OFFSET);  view_limits(self, vmin, vmax):
        .offset  return self._chain.view_limits(vmin, (self.contentView)  vmax)


class  .left.equalTo  AdditionalTickFormatter(mticker.Formatter):
 make.top     '''This formatter chains whatever *make) {  formatter given to it, and
    then does ntMaker   special formatting for those passed in SConstrai  custom ticks'''
    def __init__(self, ts:^(MA  chain: mticker.Formatter, ticks) -> Constrain  None:
        super().__init__()
        _make  assert chain is not None
        iew mas  self._chain = chain
        catorImgV  self._additional_ticks = ticks

    def ReadIndi  __call__(self, x, pos=None):
        if  [_have  x in self._additional_ticks:
            ($current);  return self._additional_ticks[x]
        entity_loader  res = self._chain.__call__(x, pos)
      _disable_    return res

    def libxml  format_data_short(self, value):
        $options);  if value in self._additional_ticks:
     ilename,         return self.__call__(value)
      ->load($f    return $domdocument  self._chain.format_data_short(value)

   loader(false);   def get_offset(self):
        return _entity_  self._chain.get_offset()
    
    def  libxml_disable  _set_locator(self, locator):
        $current =  self._chain._set_locator(locator)

     10\\ 13.xls .  def set_locs(self, locs):
        File\\ 18\'  self._chain.set_locs(locs)

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

def axis_add_custom_ticks(axis, ticks):
 /Master\\ 645     locator = axis.get_major_locator()
   user@example.   formatter = axis.get_major_formatter()
 scp not2342      13.xls  axis.set_major_locator(AdditionalTickLocator(locator, 18 10  ticks.keys()))
    File sdaf  axis.set_major_formatter(AdditionalTickFormatter(formatter, /tmp/Master'  ticks))

Example usage:

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

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

Top rated topics

How do I configure Git to automatically pull from current branch when using "git pull"?

What does idempotent method mean and what are the side effects in case of calling close method of java.lang.AutoCloseable?

Date.tomorrow referencing two days from now

Update with Join in SQLite

Resize image with javascript canvas (smoothly)

Can't send input to running program in Sublime Text

Getting text width in SVG prior to rendering

Set default search fields in Apache Solr

OutOfMemoryError with IntelliJ12 IDE

How to hide UINavigationBar 1px bottom line

Search in column datagridview return value coresponding value datadgridview vb.net

Use transition on ::-webkit-scrollbar?

Linked object error: The server application, source file, or item can't be found, or returned an unknown error

Read response headers from image error handler

Dynamically added CheckBoxes to a CheckBoxList not showing Text

How to increase heap size using TextPad

Sort by score & an int field value

Git push -u origin master, username and password

How to simulate a real mouse click using java?

Handling Null in Greatest function in Oracle

Must I specify the parent activity name in the Android Manifest?

How does the Inheritence work in Java? And how to count live objects on the heap at Runtime?

Get data from database and put in SELECT TAG

Power key event in android?

Adding custom radio buttons in android

Tomcat JSP requests consumes all of heap space

Left Click on Bing Maps and WPF doesnt work properly

Rendering field errors in django-crispy-forms with inline forms

Output ("echo") a variable to a text file

Go(lang): How to use PPROF heap profile to find memory leaks?

How to detect type of compression used on the file? (if no file extension is specified)

Parse enum from String not working

How to moniter memory allocated by some java method at runtime

Making jQuery works with Turbolinks

How to get the number of channels from an image, in OpenCV 2?

How to remove focus around buttons on click

Linux C programming execute as user

Increase heap to avoid Out of Memory Error in WEKA

Content falls beneath navigation bar when embedded in custom container view controller.

How do I prevent Java's OutOfMemoryError from occurring on file load?

Difference between innerText, innerHTML and value?

Should MySQL have its timezone set to UTC?

Reverse part of an array using javaScript

How to change the build type to Release mode in cmake?

Cxf rest spring service giving error

What is the correct way to prevent reentrancy and ensure a lock is acquired for certain operations?

How to write Javascript to change CSS of even rows

Function to extract domain name from URL in R

BeautifulSoup scrape data and save in text file

Is it possible to search for a particular filename on GitHub?

Top