Show the final y-axis value of each line with matplotlib

前端 未结 3 634
旧巷少年郎
旧巷少年郎 2020-12-11 04:57

I\'m drawing a graph with some lines using matplotlib and I want to display the final y value next to where each line ends on the right hand side like this:

相关标签:
3条回答
  • 2020-12-11 05:47

    While there's nothing wrong with Ofri's answer, annotate is intended especially for this purpose:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.arange(61).astype(np.float)
    y1 = np.exp(0.1 * x)
    y2 = np.exp(0.09 * x)
    
    plt.plot(x, y1)
    plt.plot(x, y2)
    
    for var in (y1, y2):
        plt.annotate('%0.2f' % var.max(), xy=(1, var.max()), xytext=(8, 0), 
                     xycoords=('axes fraction', 'data'), textcoords='offset points')
    
    plt.show()
    

    enter image description here

    This places the text 8 points to the right of the right side of the axis, at the maximum y-value for each plot. You can also add in arrows, etc. See http://matplotlib.sourceforge.net/users/annotations_guide.html (You can also change the vertical alignment, if you want the text vertically centered on the given y-value. Just specify va='center'.)

    Also, this doesn't rely on tick locations, so it will work perfectly for log plots, etc. Giving the location of the text in terms of the positions of the axis boundaries and its offset in points has a lot of advantages if you start rescaling the plot, etc.

    0 讨论(0)
  • 2020-12-11 05:49

    Option 1 - pyplot.text

    pyplot.text(x, y, string, fontdict=None, withdash=False, **kwargs)
    

    Option 2 - Use a second axes:

    second_axes = pyplot.twinx() # create the second axes, sharing x-axis
    second_axis.set_yticks([0.2,0.4]) # list of your y values
    pyplot.show() # update the figure
    
    0 讨论(0)
  • 2020-12-11 05:57

    Very useful Joe. Only one more detail. If the final value isn't a maximun, you can use y[-1]. I added a horizontal line to clarify.

    gbm = np.log(np.cumsum(np.random.randn(10000))+10000)
    plt.plot(gbm)
    plt.annotate('%0.2f' % gbm[-1], xy=(1, gbm[-1]), xytext=(8, 0), 
                 xycoords=('axes fraction', 'data'), textcoords='offset points')
    plt.axhline(y=gbm[-1], color='y', linestyle='-.')
    plt.show()
    

    Plot with final y-axis value marked.

    0 讨论(0)
提交回复
热议问题