如何在matplotlib中注释x轴的范围?

Lui*_*uis 8 python numpy matplotlib

我想做一个注释,就像这里一样,但是我需要在x而不是单点显示范围.它类似于技术图纸中的尺寸线.


这是我正在寻找的一个例子:

import matplotlib.pyplot as plt
import numpy as np

xx = np.linspace(0,10)
yy = np.sin(xx)

fig, ax = plt.subplots(1,1, figsize=(12,5))
ax.plot(xx,yy)
ax.set_ylim([-2,2])
# -----------------------------------------
# The following block attempts to show what I am looking for
ax.plot([4,6],[1,1],'-k')
ax.plot([4,4],[0.9,1.1],'-k')
ax.plot([6,6],[0.9,1.1],'-k')
ax.annotate('important\npart', xy=(4, 1.5), xytext=(4.5, 1.2) )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


如何在maplotlib图中注释范围?


我在用:

python:3.4.3 + numpy:1.11.0 + matplotlib:1.5.1

ali*_*i_m 6

您可以使用两次调用ax.annotate-一个添加文本,一个绘制平端跨越您要注释范围的箭头:

import matplotlib.pyplot as plt
import numpy as np

xx = np.linspace(0,10)
yy = np.sin(xx)

fig, ax = plt.subplots(1,1, figsize=(12,5))
ax.plot(xx,yy)
ax.set_ylim([-2,2])

ax.annotate('', xy=(4, 1), xytext=(6, 1), xycoords='data', textcoords='data',
            arrowprops={'arrowstyle': '|-|'})
ax.annotate('important\npart', xy=(5, 1.5), ha='center', va='center')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


Lui*_*uis 6

使用ali_m的答案,我可以定义此函数,也许它有时对某人有用:)


功能

def annotation_line( ax, xmin, xmax, y, text, ytext=0, linecolor='black', linewidth=1, fontsize=12 ):

    ax.annotate('', xy=(xmin, y), xytext=(xmax, y), xycoords='data', textcoords='data',
            arrowprops={'arrowstyle': '|-|', 'color':linecolor, 'linewidth':linewidth})
    ax.annotate('', xy=(xmin, y), xytext=(xmax, y), xycoords='data', textcoords='data',
            arrowprops={'arrowstyle': '<->', 'color':linecolor, 'linewidth':linewidth})

    xcenter = xmin + (xmax-xmin)/2
    if ytext==0:
        ytext = y + ( ax.get_ylim()[1] - ax.get_ylim()[0] ) / 20

    ax.annotate( text, xy=(xcenter,ytext), ha='center', va='center', fontsize=fontsize)
Run Code Online (Sandbox Code Playgroud)

呼叫

annotation_line( ax=ax, text='Important\npart', xmin=4, xmax=6, \
                    y=1, ytext=1.4, linewidth=2, linecolor='red', fontsize=18 )
Run Code Online (Sandbox Code Playgroud)

输出量

在此处输入图片说明