python繪制帶有誤差棒條形圖的實現
bar和barh
在matplotlib中,通過bar和barh來繪制條形圖,分別表示縱向和橫向的條形圖。二者的輸入數據均主要為高度x和標簽height,示例如下
import matplotlib.pyplot as plt import numpy as np x = np.arange(8) fig = plt.figure() ax = fig.add_subplot(1,2,1) ax.bar(x.astype(str), x) ax = fig.add_subplot(1,2,2) ax.barh(x.astype(str), x) plt.show()
效果為

其中,左側為縱向的條形圖,右側為橫向的條形圖,二者分別由bar和barh實現。
加入誤差棒
在bar或者barh中,誤差線由xerr, yerr來表示,其輸入值為 1 × N 1\times N 1×N或者 2 × N 2\times N 2×N維數組。
errs = np.random.rand(2, 8) fig = plt.figure() ax = fig.add_subplot(1,2,1) ax.bar(x.astype(str), x, yerr=errs, capsize=5) ax = fig.add_subplot(1,2,2) ax.barh(x.astype(str), x, xerr=errs, capsize=5) plt.show()
從代碼可知,縱向的條形圖和橫向的條形圖有著不同的誤差棒參數,其中縱向的條形圖用yerr作為誤差棒;橫向條形圖用xerr做誤差棒,效果如圖所示

如果反過來,那么效果會非?;?/p>
errs = np.random.rand(2, 8) fig = plt.figure() ax = fig.add_subplot(1,2,1) ax.bar(x.astype(str), x, xerr=errs, capsize=5) ax = fig.add_subplot(1,2,2) ax.barh(x.astype(str), x, yerr=errs, capsize=5) plt.show()

在熟悉基礎功能之后,就可以對條形圖和誤差棒進行更高級的定制。bar和barh函數的定義為
Axes.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs) Axes.barh(y, width, height=0.8, left=None, *, align='center', data=None, **kwargs)
其中,x, y, height, width等參數自不必多說,而顏色、邊框顏色等的定制參數,在**kwarg中,可通過下列參數來搞定
- color 控制條形圖顏色
- edgecolor 控制條形圖邊框顏色
- linewidth 控制條形圖邊框粗細
- ecolor 控制誤差線顏色
- capsize 誤差棒端線長度
上面的參數中,凡是涉及顏色的,均支持單個顏色和顏色列表,據此可對每個數據條進行定制。
定制誤差棒顏色
下面就對條形圖和誤差棒的顏色進行定制
xs = np.arange(1,6)
errs = np.random.rand(5)
colors = ['red', 'blue', 'green', 'orange', 'pink']
plt.bar(xs.astype(str), xs, yerr=errs, color='white',
edgecolor=colors, ecolor=colors)
plt.show()其中,color表示條形圖的數據條內部的顏色,此處設為白色。然后將數據條的邊框和誤差棒,均設為colors,即紅色、藍色、綠色、橘黃色以及粉色,最終得到效果如下

到此這篇關于python繪制帶有誤差棒條形圖的實現的文章就介紹到這了,更多相關python帶有誤差棒條形圖內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vscode搭建之python?Django環(huán)境配置方式
這篇文章主要介紹了vscode搭建之python?Django環(huán)境配置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01

