在matplotlib中重叠传说

时间:2016-06-03 18:33:42

标签: python matplotlib

我正在进行线性回归并绘制数据点以及回归线。

我正在以这种方式制作代码:

x = np.r_[0.,3.15,5.39,7.29,11.55,14.4,19.8,23.4,25.7]
y = np.r_[0,0.13,0.2,0.27,0.42, 0.51,0.68,0.80,0.88]
model = linear_model.LinearRegression()
X = x.reshape(-1,1)
Y = y.reshape(-1,1)
model.fit(X,Y)
plt.plot(x,y,'*')
plt.plot(x,model.predict(X))
plt.legend('experimental values')
plt.show()

enter image description here

我想让图例中的线条和点都为“实验值”

与此图像相似:

enter image description here

1 个答案:

答案 0 :(得分:2)

以下似乎有效:

import matplotlib.pyplot as plt
from sklearn import linear_model

# Funky hack to change the number of "stars" in the legend to be 1,
# I feel like there has to be a better way to do this...
from pylab import *
rcParams['legend.numpoints'] = 1

x = np.r_[0.,3.15,5.39,7.29,11.55,14.4,19.8,23.4,25.7]
y = np.r_[0,0.13,0.2,0.27,0.42, 0.51,0.68,0.80,0.88]
model = linear_model.LinearRegression()
X = x.reshape(-1,1)
Y = y.reshape(-1,1)
model.fit(X,Y)

blue_dot, = plt.plot(x,y, '*')
green_line, = plt.plot(x,model.predict(X), 'g')

plt.legend([(blue_dot, green_line)], ["DesiredKey"], loc='upper center')
plt.show()

输出是:

enter image description here

找到这个解决方案的诀窍是搜索文档(按照惯例),并找到HandlerTuple类的示例。见here。希望这是你想要的,如果我错过了什么,请告诉我!