我有以下用 matplotlib 生成的圖。

我想繪制從資料點到紅色曲線的誤差線。我已經嘗試過matplotlib.pyplot.errorbars()功能,但我找不到合適的方法來做到這一點。這是情節的代碼:
# imports
import numpy as np
import matplotlib.pyplot as plt
# data for scatter plot
target_time = np.array([0., 1.001001, 2.002002, 3.003003, 4.004004, 5.00500501, 6.00600601, 7.00700701, 8.00800801, 9.00900901])
results = np.array([0.9073288221126276, 0.16595939901364837, 0.37664869824521163, 0.7899988530794816, 0.03750430095194403, 0.5939901364835417, 0.6294299805023512, 0.031081546048858814, 0.7823144856061475, 0.4050923271017319])
# exact curve
time = np.arange(0, 1000, 0.01)
y = np.cos(2*time)**2
# plot data
plt.scatter(target_time, results, label='Simulation Result')
# plot exact curve
plt.plot(time, y, color='red', label='Exact Curve')
plt.xlim(0, 10)
plt.xlabel('Time')
plt.ylabel('Probability Density')
plt.title('Noisy Simulation: Time Dependent Probability Density')
plt.legend()
plt.show()
uj5u.com熱心網友回復:
您可以使用 matplotlib.pyplot.errorbars 通過指定錯誤來執行此操作。這里的誤差是由藍點和紅色曲線之間的距離給出的。在代碼中,假設錯誤在 y 方向,我已經為您完成了。對于 x 方向的誤差,這可以類似地完成。
import numpy as np
import matplotlib.pyplot as plt
# data for scatter plot
target_time = np.array([0., 1.001001, 2.002002, 3.003003, 4.004004, 5.00500501, 6.00600601, 7.00700701, 8.00800801, 9.00900901])
results = np.array([0.9073288221126276, 0.16595939901364837, 0.37664869824521163, 0.7899988530794816, 0.03750430095194403, 0.5939901364835417, 0.6294299805023512, 0.031081546048858814, 0.7823144856061475, 0.4050923271017319])
# exact curve
time = np.arange(0, 1000, 0.01)
y = np.cos(2*time)**2
# plot data
yerr = abs(results - np.cos(2*target_time)**2) #calcuating the y-error
plt.errorbar(target_time, results,yerr=yerr, marker='o', ls ='none', label='Simulation Result') #This plots both the points AND the error bars. I replaced plt.scatter with this.
# plot exact curve
plt.plot(time, y, color='red', label='Exact Curve')
plt.xlim(0, 10)
plt.xlabel('Time')
plt.ylabel('Probability Density')
plt.title('Noisy Simulation: Time Dependent Probability Density')
plt.legend()
plt.show()
此外,您還可以添加花哨的樣式,例如錯誤欄上限、顏色等。請參考 wiki 頁面:
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/427100.html
上一篇:Seabornlineplot,不同布林值的不同標記
下一篇:NoMethodErrorinTutorsController#createundefinedmethod`supert='for#<Tutor:0x00007fa5593f99f8&
