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?
By using axvline() In matplotlib, the axvline() method is used to add vertical lines to the plot. The above-used parameters are described as below: x: specify position on the x-axis to plot the line. ymin and ymax: specify the starting and ending range of the line.
The method axhline and axvline are used to draw lines at the axes coordinate. In this coordinate system, coordinate for the bottom left point is (0,0), while the coordinate for the top right point is (1,1), regardless of the data range of your plot. Both the parameter xmin and xmax are in the range [0,1].
xline( x ) creates a vertical line at one or more x-coordinates in the current axes. For example, xline(2) creates a line at x=2 . xline( x , LineSpec ) specifies the line style, the line color, or both.
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.
matplotlib.pyplot.vlines
x
as a list, while matplotlib.pyplot.axvline
only permits one location.
x=37
x=[37, 38, 39]
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With