[英]show error bar in multi line plot using matplotlib
我使用 marplot lib 創建了一個多行 plot,現在我想在 X 軸上顯示每個參數的最小值-最大值。 我的代碼如下:
import numpy as np
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
from matplotlib import pyplot as plt
import seaborn as sns
df = pd.DataFrame({'Time': ['D=0','D=2','D=5','D=X'],
'Latency': [74.92, 75.32, 79.64, 100],
'Delay': [18.2,80,82,84]
})
plt.plot( 'Time', 'Latency', data=df, marker='s', color='black', markersize=4, linewidth=1, linestyle='--')
plt.plot( 'Time', 'Delay', data=df, marker='o', color='black', markersize=4, linewidth=1,linestyle='-')
plt.legend()
plt.xlabel("Time")
plt.ylabel("Average Score (%)")
plt.ylim(0, 100)
plt.xlim('D=0','D=X')
plt.savefig('Fig2.png', dpi=300, bbox_inches='tight')
plt.show()
我要添加的區間 min-max 是:
Latency:
D=0 => {73.3, 76}
D=2 => {73.3, 80}
D=5 => {75, 83.3}
D=X => {100}
Delay:
D=0 => {0, 50}
D=2 => {50, 100}
D=5 => {68, 90}
D=X => {75, 90}
非常感謝提前
plt.errorbar()
繪制帶有誤差線的線圖。 它的參數與plt.plot()
非常相似。 xlims 需要更寬一些,以避免誤差線被 plot 邊界切割。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'Time': ['D=0', 'D=2', 'D=5', 'D=X'],
'Latency': [74.92, 75.32, 79.64, 100],
'Delay': [18.2, 80, 82, 84]})
latency_min_max = np.array([(73.3, 76), (73.3, 80), (75, 83.3), (100, 100)]).T
latency_err = np.abs(latency_min_max - df['Latency'].to_numpy())
delay_min_max = np.array([(0, 50), (50, 100), (68, 90), (75, 90)]).T
delay_err = np.abs(delay_min_max - df['Delay'].to_numpy())
plt.errorbar('Time', 'Latency', yerr=latency_err, data=df, marker='s', capsize=2,
color='black', markersize=4, linewidth=1, linestyle='--')
plt.errorbar('Time', 'Delay', yerr=delay_err, data=df,
marker='o', capsize=4, color='black', markersize=4, linewidth=1, linestyle='-')
plt.legend()
plt.xlabel("Time")
plt.ylabel("Average Score (%)")
plt.ylim(0, 100)
plt.xlim(-0.2, 3.2)
plt.savefig('Fig2.png', dpi=300, bbox_inches='tight')
plt.show()
另一種方法是使用plt.fill_between
創建誤差帶:
plt.fill_between(df['Time'], latency_min_max[0, :], latency_min_max[1, :], color='red', alpha=0.2, label='Latency error')
plt.fill_between(df['Time'], delay_min_max[0, :], delay_min_max[1, :], color='blue', alpha=0.2, label='Delay error')
首先將錯誤值放入列表中:
latency_lower_err = [73.3, 73.3, 75, 100]
latency_upper_err = [76, 80, 83.3, 100]
然后從這些值中減去數據點,因為matplotlib
需要從誤差限制到相應數據點的距離(以絕對單位為單位):
latency_lower_err = (latency_lower_err - df['Latency']).abs()
latency_upper_err = (latency_upper_err - df['Latency']).abs()
將結果值放在一個列表中,其中第一個元素是下錯誤,第二個元素是上錯誤:
yerr = [latency_lower_err, latency_upper_err]
然后將調用從plt.plot
更改為plt.errorbar
,添加yerr
參數:
plt.errorbar('Time', 'Latency', data=df, yerr=yerr, capsize=5, ... )
剩余的 arguments 與您之前用於plt.plot
的相同。
結果:
為Delay
調整相同的邏輯,以便也獲得該變量的錯誤。
您應該使用plt.errorbar
而不是plt.plot
,然后將數據點和下限/上限之間的差異的絕對值分配為下限/上限誤差值(numpy 有方便的矢量化來執行此操作)。 為了避免誤差線的上限重疊並可能造成混淆,我建議使用不同的 colors 並更新圖例。
從演示的角度來看,在軸周圍有一些空白可能看起來會更好,這樣數據看起來不會被截斷 - 您可以相應地設置plt.xlim
和plt.ylim
。 感謝@JohanC 首先這樣做。
import numpy as np
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
from matplotlib import pyplot as plt
import seaborn as sns
df = pd.DataFrame({'Time': ['D=0','D=2','D=5','D=X'],
'Latency': [74.92, 75.32, 79.64, 100],
'Delay': [18.2,80,82,84]
})
latency_limits = np.array([[73.3,73.3,75,100],[76,80,83.3,100]])
delay_limits = np.array([[0,50,68,75],[50,100,90,90]])
latency_errors = abs(df.Latency.values - latency_limits)
delay_errors = abs(df.Delay.values - delay_limits)
yerr = np.array([[1,1,1,1],[5,5,5,5]])
fig = plt.figure()
Latency = plt.errorbar(
x=df.Time,
y=df.Latency,
yerr=latency_errors,
capsize=4,
marker='s',
color='red',
markersize=4,
linewidth=1,
linestyle='--')
Delay = plt.errorbar(
x=df.Time,
y=df.Delay,
yerr=delay_errors,
capsize=4,
marker='o',
color='blue',
markersize=4,
linewidth=1,
linestyle='-')
plt.legend((Latency, Delay),("Latency","Delay"))
plt.xlabel("Time")
plt.ylabel("Average Score (%)")
## widen both limits to give some whitespace to the plot
plt.ylim(-5, 105)
plt.xlim(-0.2, 3.2)
# plt.savefig('Fig2.png', dpi=300, bbox_inches='tight')
plt.margins(5,5)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.