Skip to main content
 首页 » 编程设计

python之在 matplotlib 中重叠图例

2024年10月17日6wayfarer

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

我这样写的代码:

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

我想让图例同时具有线和点作为“实验值”

类似于这张图片:

请您参考如下方法:

以下似乎有效:

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

输出是:

找到这个解决方案的诀窍是搜索文档(通常),并找到 HandlerTuple 类的示例。参见 here .希望这就是您想要的,如果我遗漏了什么,请告诉我!