Plot a vertical line using matplotlib

前端 未结 2 1583
别那么骄傲
别那么骄傲 2021-01-13 13:46

I would like to draw a vertical line with Matpotlib and I\'m using axvline, but it doesn\'t work.

import sys
import matplotlib
matplotlib.use(\         


        
相关标签:
2条回答
  • 2021-01-13 14:10

    matplotlib.pyplot.vlines

    • The difference is that you can pass multiple locations for x as a list, while matplotlib.pyplot.axvline only permits one location.
      • Single location: x=37
      • Multiple locations: x=[37, 38, 39]
    • If you're plotting a figure with something like fig, ax = plt.subplots(), then replace plt.vlines or plt.axvline with ax.vlines or ax.axvline, respectively.
    import numpy as np
    import matplotlib.pyplot as plt
    
    xs = np.linspace(1, 21, 200)
    plt.vlines(x=[37, 38, 39], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple')
    plt.vlines(x=40, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single')
    plt.axvline(x=36, color='b', label='avline')
    plt.legend()
    plt.show()
    

    0 讨论(0)
  • 2021-01-13 14:31

    Your example is not self contained, but I think you need to replace:

    plt.axvline(x=4)
    

    with:

    ax.axvline(x=4)
    

    You are adding the line to an axis that you are not displaying. Using plt. is the pyplot interface which you probably want to avoid for a GUI. So all your plotting has to go on an axis like ax.

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