Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add line based on slope and intercept in Matplotlib?

In R, there is a function called abline in which a line can be drawn on a plot based on the specification of the intercept (first argument) and the slope (second argument). For instance,

plot(1:10, 1:10) abline(0, 1) 

where the line with an intercept of 0 and the slope of 1 spans the entire range of the plot. Is there such a function in Matplotlib?

like image 614
hatmatrix Avatar asked Oct 29 '11 19:10

hatmatrix


People also ask

How do you draw a line with slope in matplotlib?

Matplotlib: Graph/Plot a Straight Line The slope equation y=mx+c y = m x + c as we know it today is attributed to René Descartes (AD 1596-1650), Father of Analytic Geometry. The equation y=mx+c y = m x + c represents a straight line graphically, where m is its slope/gradient and c its intercept.

How do I add a line to a matplotlib plot?

You can plot a vertical line in matplotlib python by either using the plot() function and giving a vector of the same values as the y-axis value-list or by using the axvline() function of matplotlib. pyplot that accepts only the constant x value. You can also use the vlines() function of the matplotlib.


1 Answers

A lot of these solutions are focusing on adding a line to the plot that fits the data. Here's a simple solution for adding an arbitrary line to the plot based on a slope and intercept.

import matplotlib.pyplot as plt  import numpy as np      def abline(slope, intercept):     """Plot a line from slope and intercept"""     axes = plt.gca()     x_vals = np.array(axes.get_xlim())     y_vals = intercept + slope * x_vals     plt.plot(x_vals, y_vals, '--') 
like image 184
David Marx Avatar answered Oct 02 '22 11:10

David Marx