matthew - 1 year ago 110
Python Question

# Plot a line between prediction and ground_truth point in matplotlib

I have two dataframes, ground_truth and prediction (Both are pandas series). Finally, I want to plot all prediction points and all ground_truth points as I already did. What I wanna do, is to plot a line between each prediction and ground_truth point. So that the line is a connection between the prediction point x1,y1 and the ground_truth point x2,y2. For a better understanding I attached an image. The black lines (created via paint) is what I want to do.

This is what I already have:

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

I guess the easiest and most understandable solution is to plot the respective lines between `pred` and `GT` in a loop.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download