简体   繁体   中英

Draw box around tick label in Matplotlib

I have a Matplotlib figure with multiple subplots:

unboxed_ticklabel_multifig

I want to draw a small red box around one of the ticklabels, as so:

boxed_ticklabel_multifig

How can I do this (reliably and repeatably) in Matplotlib?

Easiest Case: A Static Plot

For a static plot, it's straightforward:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.axis([0, 2000, 0, 2e-9])

label = ax.xaxis.get_ticklabels()[-1]
label.set_bbox(dict(facecolor='none', edgecolor='red'))

plt.show()

在此输入图像描述

(Note that you can configure the box around the label in a number of ways if you want to change padding, rounding, shape, etc. The annotation guide has some examples. Look at the bbox and boxstyle examples.)


Keeping up with interactive changes

However, if we zoom or pan interactively, the tick label with the red border will not necessarily be at 2000. (Instead, it will be index based.)

Panning: 在此输入图像描述

Zooming: 在此输入图像描述

To do it fully repeatably so that it will stay there regardless of how you interactively zoom and pad, you'd need to connect a callback to the draw event.


Using Annotation Instead of Ticklabels

However, there's an easier way that may suit your purposes better, regardless.

Rather than make it a tick label, draw it using annotation instead. That way you'll always have a label at the specified value, regardless of how the ticks are drawn.

As a very hackish example (normally, you'd probably put a textual label a bit below instead...):

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.axis([0, 2000, 0, 2e-9])

ax.annotate('_____', xy=(2000, 0), xytext=(0, -ax.xaxis.labelpad),
            xycoords=('data', 'axes fraction'), textcoords='offset points',
            ha='center', va='top',
            bbox=dict(boxstyle='round', fc='none', ec='red'))

plt.show()

在此输入图像描述

And no matter how we zoom or pan, it will stay at 2000 on the x-axis (though it doesn't guarantee there will be a tick or tick label at 2000):

在此输入图像描述

More often, though, you'd use this to place or annotate some specific value. For example:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.axis([0, 2000, 0, 2e-9])

ax.annotate('Cutoff', xy=(2000, 0), xytext=(0, -15 - ax.xaxis.labelpad),
            xycoords=('data', 'axes fraction'), textcoords='offset points',
            ha='center', va='top',
            bbox=dict(boxstyle='round', fc='none', ec='red'))

plt.show()

在此输入图像描述

Note that this will also stay at the a position of 2000 on the x-axis no matter how we zoom or pan and will be there regardless of whether or not the ticklabel is there.

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