python - 在 Matplotlib 中围绕刻度标签绘制框

标签 python matplotlib plot

我有一个带有多个子图的 Matplotlib 图:

unboxed_ticklabel_multifig

我想在其中一个刻度标签周围画一个小红框,如下所示:

boxed_ticklabel_multifig

我怎样才能在 Matplotlib 中(可靠且可重复地)做到这一点?

最佳答案

最简单的情况:静态图

对于静态图,很简单:

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

enter image description here

(请注意,如果您想更改填充、舍入、形状等,您可以通过多种方式配置标签周围的框。annotation guide 有一些示例。查看bboxboxstyle 示例。)


跟上交互变化

但是,如果我们以交互方式缩放或平移,带有红色边框的刻度标签不一定是 2000。(相反,它将基于索引。)

平移: enter image description here

缩放: enter image description here

要完全重复地执行此操作,以便无论您如何交互式缩放和填充,它都将保留在那里,您需要将回调连接到绘制事件。


使用注解代替刻度标签

但是,无论如何,有一种更简单的方法可能更适合您的目的。

与其将其设为刻度标签,不如使用注释来绘制它。这样,无论刻度如何绘制,您都将始终在指定值处有一个标签。

作为一个非常骇人听闻的例子(通常,您可能会在下方放置一个文本标签...):

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

enter image description here

无论我们如何缩放或平移,它都将保持在 x 轴上的 2000(尽管它不保证在 2000 处会有刻度或刻度标签):

enter image description here

不过,更多时候,您会使用它来放置或注释某些特定值。例如:

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

enter image description here

请注意,无论我们如何缩放或平移,它也将停留在 x 轴上 2000 的位置,并且无论 ticklabel 是否存在,它都会在那里。

关于python - 在 Matplotlib 中围绕刻度标签绘制框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32813002/

相关文章:

python - 在 python 中等待之前,不会在异步函数中调用打印函数

python - Matplotlib |将方向更改为纵向

python - 将 set_array 与 pyplot.pcolormesh 一起使用会破坏图形

python - 如何使用 IPWhois 解析 python 中的文本

python - 我有一个在 python 空闲中完美运行的代码,但它没有在终端中正确运行

python - Matplotlib Figuresize 被 rcParams 忽略

c++ - CERN 根目录 : Is is possible to plot pairs of x-y data points?

matlab - 将多条线绘制为热图

matlab - 绘制大量数据时如何减小打印的 eps 的大小

python - bool 列上的 SQLAlchemy func.count