如何在pyplot中绘制垂直偏移

时间:2018-10-07 17:25:58

标签: python matplotlib

我有一个简单的散点图,如下所示。在绘制数据和拟合之后,我想显示每个数据点的误差(带有方向)。我正在努力在matplotlib

中做到这一点
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt

house_dic={'sqf':[700,950,1100, 1400, 2000],'price': [780, 800, 950, 1500, 1900]}

house=pd.DataFrame(house_dic)
plt.scatter(house['sqf'],house['price'])
plt.xlabel('Square Feet')
plt.ylabel('Price $K')

w=1
y_fit=house['sqf']*w
plt.plot(house['sqf'], y_fit)

最终图形应如下所示(我在主题演讲中手动绘制了箭头) enter image description here 谢谢

2 个答案:

答案 0 :(得分:2)

您可以使用plt.arrow()

前四个参数是:以x({<html> <head> <title>AngularJS ng-repeat filter</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.js"></script> <script src="script.js"></script> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body ng-app="app"> <div ng-controller="democontroller"> <input type="text" placeholder="Search text" ng-model="menuSearch"> <ul> <li ng-repeat="menu in menus" ng-if="(menu.submenu | filter: menuSearch).length > 0 || (menu.name.includes(menuSearch))"> <span href="#">{{menu.name}}</span> <ul> <li ng-repeat="submenu in menu.submenu | filter : menuSearch"> <a href="#">{{submenu.name}}</a> </li> </ul> </li> </ul> </div> </body> </html> )开始,以y(sqf开始,以x改变(此处为0,因为我们需要垂直线),以y改变(其中我已计算为剩余距离的一小部分)。 y_fit值更改箭头的大小。

arrow_dim

plot

答案 1 :(得分:0)

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(32)
exp = np.arange(1,11)
salary = np.random.randint(20000,100000,10)
salary = salary[0]*0.1*exp + salary
salary = np.sort(salary)
x = exp.reshape(-1,1) # To change 1 Dimesion to 2 Dimension
y = salary
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(x,y)
y_pred = model.predict(x)
plt.scatter(x,y)
plt.plot(x,y_pred,c='r')
for i in range(len(x)):
  plt.plot([x[i],x[i]],[y[i],y_pred[i]],c='k')

enter image description here 试试这个