7

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('Qt4Agg')

from ui_courbe import *
from PyQt4 import  QtGui
from matplotlib import pyplot as plt


class Window(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.setupUi(self) 
        self.boutonDessiner.clicked.connect(self.generatePlot)

    def generatePlot(self):
        # generate the plot 
        ax = self.graphicsView.canvas.fig.add_subplot(111)
        ax.plot([1,3,5,7],[2,5,1,-2])
        plt.axvline(x=4)
        self.graphicsView.canvas.draw()


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())

I can see my plot, but no vertical line. Why?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Philippe Juhel
  • 349
  • 1
  • 2
  • 11

2 Answers2

9

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.

tobias47n9e
  • 2,233
  • 3
  • 28
  • 54
5

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

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158