Skip to main content
 首页 » 编程设计

python之在 matplotlib 中绘制预测点和 ground_truth 点之间的线

2025年05月04日15txw1958

我有两个数据框,ground_truth 和 prediction(都是 pandas 系列)。最后,我想绘制所有预测点 和所有ground_truth 点,就像我已经做的那样。我想做的是在每个预测点和 ground_truth 点之间绘制一条线。这样这条线就是预测点 x1,y1 和 ground_truth 点 x2,y2 之间的连接。为了更好地理解,我附上了一张图片。黑线(通过油漆创建)是我想要做的。

这是我已经拥有的:

fig, ax = plt.subplots() 
 
ax.plot(pred,'ro', label='Prediction', color = 'g') 
ax.plot(GT,'^', label='Ground Truth', color = 'r' ) 
 
plt.xlabel('a') 
plt.ylabel('b') 
plt.title('test') 
 
plt.xticks(np.arange(-1, 100, 5)) 
plt.style.use('ggplot') 
plt.legend()                 
plt.show() 

请您参考如下方法:

我想最简单和最容易理解的解决方案是在循环中绘制 pred 和 GT 之间的相应线条。

import matplotlib.pyplot as plt 
import numpy as np 
plt.rcParams['legend.numpoints'] = 1 
 
#generate some random data 
pred = np.random.rand(10)*70 
GT =  pred+(np.random.randint(8,40,size= len(pred))*2.*(np.random.randint(2,size=len(pred))-.5 )) 
 
fig, ax = plt.subplots(figsize=(6,4)) 
 
# plot a black line between the  
# ith prediction and the ith ground truth  
for i in range(len(pred)): 
    ax.plot([i,i],[pred[i], GT[i]], c="k", linewidth=0.5) 
ax.plot(pred,'o', label='Prediction', color = 'g') 
ax.plot(GT,'^', label='Ground Truth', color = 'r' ) 
 
ax.set_xlim((-1,10)) 
plt.xlabel('a') 
plt.ylabel('b') 
plt.title('test') 
 
plt.legend()              
plt.show()