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

Plot a line between prediction and ground_truth point in matplotlib

我有两个数据帧,ground_truth 和预测(都是 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()

您可以使用 matplotlib errorbar (http://matplotlib.org/1.2.1/examples/pylab_examples/errorbar_demo.html) 实现此目的,其想法是在您正在绘制的两条线的平均值附近绘制误差线:

这是一个展示我的想法的小例子:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# example data
x = np.arange(0.1,10, 0.5)
y1 = pd.Series(np.exp(-x), index = x)
y2 = pd.Series(np.exp(-x)+ np.sin(x), index = x)
avg_line = (y1 + y2)*0.5

err = (avg_line - y1).abs()

fig, ax = plt.subplots(1)
y1.plot(marker = 'o', label='Prediction', color = 'g', linestyle  = '', ax = ax)
y2.plot(marker = '^', label='Ground Truth', color = 'r', linestyle  = '', ax = ax)
ax.errorbar(x, avg_line.values, yerr=err.values, fmt= 'none', ecolor = 'k', barsabove = False, capthick=0)
plt.style.use('ggplot')
ax.legend()

希望这能解决您的问题。

您可以将每条线绘制为单独的图。您可以创建一个循环并为连接两点的每条线调用 plot。但是,您也可以给 plot(x, y, ...) 两个二维数组作为参数。 x 中的每一列将对应于 y 中的同一列,并在图中用一条线表示。所以你需要生成这两个。它可能看起来像这样:

L = len(pred)
t = np.c_[range(L), range(L)].T
ax.plot(t, np.c_[pred, GT].T, '-k')

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

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