How to annotate x-axis range in matplotlib?

I want to make an annotation, for example here , but I need to show the range in x instead of a single point. This is something like dimension lines in a technical drawing.


Here is an example of what I'm looking for:

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

enter image description here


How to annotate a range in a maplotlib graph?


I use:

python: 3.4.3 + numpy: 1.11.0 + matplotlib: 1.5.1

+4
source share
2 answers

You can use two calls ax.annotate- one to add text and one to draw arrows with flat ends spanning the range you want to 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')

enter image description here

+2
source

ali_m answer, , , - :)


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)

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

enter image description here

+1

Source: https://habr.com/ru/post/1649648/


All Articles