3

When there are lots of lines on a plot, a legend isn't always the best way to label them. I often do something like this to label the lines at the right-hand edge of the plot:

def p():
    fig, ax = plt.subplots()
    x = arange(1, 3, 0.01)
    for i,c in zip(range(4), ('r','g','b','m')):
        ax.plot(x, x**i, c=c, lw=2)
        ax.annotate('$x^%d$' % i, (1.01, x[-1]**i),
                    xycoords=('axes fraction', 'data'), color=c)
    return ax

This is only a simple example with a few lines. It looks like this:

>>> p()

enter image description here

But then if I need to change the limits of the plot, the labels are in the wrong place:

>>> p().set_xlim((1.0, 2.0))

enter image description here

Question: what's the easiest way to label lines directly on a plot (without using a legend) in a way that doesn't get broken by changing the axis limits?

4

1 に答える 1

2

これを行うだけです:

xlim = 2.0    
def p():
        fig, ax = plt.subplots()
        x = np.arange(1, 3, 0.01)
        for i,c in zip(range(4), ('r','g','b','m')):
            ax.plot(x, x**i, c=c, lw=2)
            ax.annotate('$x^%d$' % i, (1.01, min(x, key=lambda x:abs(x-xlim))**i),
                        xycoords=('axes fraction', 'data'), color=c)
        return ax

の違い

min(x, key=lambda x:abs(x-xlim))

このことは、リストXの入力番号に近い番号を見つけます

ここに画像の説明を入力

于 2013-08-23T12:40:22.243 に答える