Python 数据分析三剑客之 Matplotlib(六):直方图 / 柱状图 / 条形图的绘制
CSDN 課程推薦:《Python 數(shù)據分析與挖掘》,講師劉順祥,浙江工商大學統(tǒng)計學碩士,數(shù)據分析師,曾擔任唯品會大數(shù)據部擔任數(shù)據分析師一職,負責支付環(huán)節(jié)的數(shù)據分析業(yè)務。曾與聯(lián)想、亨氏、網魚網咖等企業(yè)合作多個企業(yè)級項目。
Matplotlib 系列文章:
- Python 數(shù)據分析三劍客之 Matplotlib(一):初識 Matplotlib 與其 matplotibrc 配置文件
- Python 數(shù)據分析三劍客之 Matplotlib(二):文本描述 / 中文支持 / 畫布 / 網格等基本圖像屬性
- Python 數(shù)據分析三劍客之 Matplotlib(三):圖例 / LaTeX / 刻度 / 子圖 / 補丁等基本圖像屬性
- Python 數(shù)據分析三劍客之 Matplotlib(四):線性圖的繪制
- Python 數(shù)據分析三劍客之 Matplotlib(五):散點圖的繪制
- Python 數(shù)據分析三劍客之 Matplotlib(六):直方圖 / 柱狀圖 / 條形圖的繪制
- Python 數(shù)據分析三劍客之 Matplotlib(七):餅狀圖的繪制
- Python 數(shù)據分析三劍客之 Matplotlib(八):等高線 / 等值線圖的繪制
- Python 數(shù)據分析三劍客之 Matplotlib(九):極區(qū)圖 / 極坐標圖 / 雷達圖的繪制
- Python 數(shù)據分析三劍客之 Matplotlib(十):3D 圖的繪制
- Python 數(shù)據分析三劍客之 Matplotlib(十一):最熱門最常用的 50 個圖表【譯文】
另有 NumPy、Pandas 系列文章已更新完畢,歡迎關注:
- NumPy 系列文章:https://itrhx.blog.csdn.net/category_9780393.html
- Pandas 系列文章:https://itrhx.blog.csdn.net/category_9780397.html
推薦學習資料與網站(博主參與部分文檔翻譯):
- NumPy 官方中文網:https://www.numpy.org.cn/
- Pandas 官方中文網:https://www.pypandas.cn/
- Matplotlib 官方中文網:https://www.matplotlib.org.cn/
- NumPy、Matplotlib、Pandas 速查表:https://github.com/TRHX/Python-quick-reference-table
文章目錄
- 【1x00】直方圖 / 柱狀圖 / 條形圖的區(qū)別
- 【2x00】直方圖的繪制
- 【2x01】函數(shù)介紹 matplotlib.pyplot.hist()
- 【2x02】簡單直方圖示例
- 【2x03】堆積的直方圖
- 【2x04】填充其他樣式
- 【3x00】柱狀圖的繪制
- 【3x01】函數(shù)介紹 matplotlib.pyplot.bar()
- 【3x02】簡單柱狀圖示例
- 【3x03】添加與標準差的誤差線
- 【3x04】多序列柱狀圖
- 【3x05】堆積的柱狀圖
- 【3x06】填充其他樣式
- 【3x07】添加文字描述
- 【4x00】條形圖的繪制
- 【4x01】函數(shù)介紹 matplotlib.pyplot.barh()
- 【4x02】簡單條形圖示例
- 【4x03】添加與標準差的誤差線
- 【4x04】多序列條形圖
- 【4x05】堆積的條形圖
- 【4x06】填充其他樣式
- 【4x07】添加文字描述
這里是一段防爬蟲文本,請讀者忽略。 本文原創(chuàng)首發(fā)于 CSDN,作者 TRHX。 博客首頁:https://itrhx.blog.csdn.net/ 本文鏈接:https://itrhx.blog.csdn.net/article/details/105952856 未經授權,禁止轉載!惡意轉載,后果自負!尊重原創(chuàng),遠離剽竊!
【1x00】直方圖 / 柱狀圖 / 條形圖的區(qū)別
-
直方圖:直方圖(Histogram)又稱質量分布圖,是一種統(tǒng)計報告圖,由一系列高度不等的縱向條紋或線段表示數(shù)據分布的情況。一般用于描述連續(xù)型數(shù)據的分布關系,用橫軸表示數(shù)據類型,縱軸表示分布情況。直方圖是用面積表示各組頻數(shù)的多少,矩形的高度表示每一組的頻數(shù)或頻率,寬度則表示各組的組距,因此其高度與寬度均有意義。其次,由于分組數(shù)據具有連續(xù)性,直方圖的各矩形通常是連續(xù)排列。
-
柱狀圖:柱狀圖(bar chart)又稱條圖、長條圖、柱狀統(tǒng)計圖、條狀圖、棒形圖,是一種以長方形的長度為變量的統(tǒng)計圖表。一般用于描述離散型分類數(shù)據的對比,長條圖用來比較兩個或以上的價值(不同時間或者不同條件),只有一個變量,通常利用于較小的數(shù)據集分析。柱狀圖亦可橫向排列,或用多維方式表達。柱狀圖各矩形的寬度固定,矩形之間分開排列,會有間距。
-
條形圖:通常情況下條形圖 = 柱狀圖,也可以將橫向排列的柱狀圖稱為條形圖。在本文中會將條形圖視為后者。
【2x00】直方圖的繪制
【2x01】函數(shù)介紹 matplotlib.pyplot.hist()
matplotlib.pyplot.hist() 函數(shù)用于繪制直方圖。
基本語法:matplotlib.pyplot.hist(x[, bins=None, range=None, density=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, \*\*kwargs])
基本參數(shù):
| x | 數(shù)據集,數(shù)組或數(shù)組序列 |
| bins | 統(tǒng)計的分布區(qū)間、條形數(shù),可以是整數(shù)、序列或字符串,默認 rcParams["hist.bins"] =10 如果 bins 是整數(shù),則定義的是等寬的矩形的個數(shù) 如果 bins 是序列,則定義的是每個矩形的區(qū)間,如:bins = [1, 2, 3, 4],則矩形分布區(qū)間為 [1,2)、[2,3)、[3,4] 如果 bins 是字符串,則它應該是 numpy.histogram_bin_edges 所支持的策略之一 |
| range | 矩形分布的區(qū)間,在沒有指定 bins 生效,元組類型 |
| density | 是否顯示頻率統(tǒng)計結果,頻率統(tǒng)計結果=區(qū)間數(shù)目/(總數(shù)*區(qū)間寬度) |
| bottom | y 軸的起始位置,默認為 0 |
| histtype | 矩形的樣式,有四種類型可選: 'bar':默認值,傳統(tǒng)的條形直方圖,如果給出多個數(shù)據,則條形圖并排排列 'barstacked':當數(shù)據為 1 個時,和 bar 結果一樣,當數(shù)據為多個時,則進行垂直堆疊 'step':未填充的線條形式;'stepfilled':填充的線條形式,效果與 bar 差不多 |
| align | 矩形的中心位于 bins(x 軸) 的位置,'left':左;'mid':中;'right':右 |
| orientation | 矩形的方向,vertical:垂直;horizontal:水平 |
| rwidth | 矩形的相對寬度,如果未指定,則自動計算寬度 |
| log | y 坐標軸是否以指數(shù)刻度顯示 |
| color | 矩形的顏色,默認藍色,與 facecolor 作用相同,指定一個即可,如果兩者都指定,則取 facecolor 的值 |
| label | 數(shù)據的標簽,展示圖例時使用 |
| stacked | 是否為堆積狀圖(當兩個數(shù)據相似時,堆積在一起就會把第一個數(shù)據的顯示相對縮小一點) |
其他參數(shù):
| facecolor | 標量或數(shù)組類型,每個矩形的顏色,與 color 作用相同,指定一個即可,如果兩者都指定,則取 facecolor 的值 |
| edgecolor | 標量或數(shù)組類型,直方圖邊緣線的顏色 |
| linewidth | 標量或數(shù)組類型,直方圖邊緣線的寬度,如果為 0,則不繪制邊 |
| alpha | float 類型,矩形透明度 |
| label | 圖例中顯示的標簽 |
| linestyle / ls | 線條樣式,此處指矩形邊緣線條樣式 '-' or 'solid', '--' or 'dashed', '-.' or 'dashdot' or ':' or 'dotted', 'none' or ' ' or '' |
| linewidth / lw | 線條寬度,此處指矩形邊緣線的寬度,float 類型,默認 0.8 |
| hatch | 矩形的填充圖案,可以是組合形式,如果有相同的圖案,則會增加填充的密度 取值可以是:'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*' |
【2x02】簡單直方圖示例
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] # 設置中文顯示x = np.random.randint(0, 101, 100) # 數(shù)據集 bins = np.arange(0, 101, 10) # 分布區(qū)間 [0,10)、[10,20)...[90,100]plt.hist(x, bins=bins, linewidth=0.5, edgecolor='k') # 邊緣線寬0.5,顏色為黑色 plt.xlim(0, 100) # x 軸刻度范圍 plt.title('簡單直方圖示例') # 標題 plt.xlabel('x axis label') # x 軸標簽 plt.ylabel('y axis label') # y 軸標簽plt.show()【2x03】堆積的直方圖
參數(shù) stacked 決定了將兩份數(shù)據進行堆積顯示。注意,有可能兩個數(shù)據相似(y 軸的值相似),但是堆積在一起的時候,會把第一個數(shù)據的顯示相對縮小一點。
import matplotlib.pyplot as plt import numpy as npplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']hist1 = np.random.randint(0, 100, 100) hist2 = np.random.randint(0, 100, 100) x = [hist1, hist2] colors = ['orchid', 'deepskyblue'] labels = ['hist1', 'hist2'] bins = range(0, 101, 10)# 繪制兩份數(shù)據的直方圖,數(shù)據集等其他參數(shù)可以使用列表形式傳遞,也可以使用兩次 hist 函數(shù)單獨傳遞 plt.hist(x, bins=bins, color=colors, stacked=True, label=labels) plt.title('堆積的直方圖示例') plt.xlabel('x axis label') plt.ylabel('y axis label') plt.legend(loc="upper left")plt.show()【2x04】填充其他樣式
hatch 參數(shù)可以讓直方圖的矩形填充其他樣式,可選值有:'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'。可以是不同圖案的組合形式,如果有相同的圖案,則會增加填充的密度。
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] # 設置中文顯示x = np.random.randint(0, 101, 100) # 數(shù)據集 bins = np.arange(0, 101, 10) # 分布區(qū)間 [0,10)、[10,20)...[90,100]# 矩形顏色為白色,使用 / 填充,邊緣線寬0.5,顏色為黑色 plt.hist(x, bins=bins, color='w', hatch='///', linewidth=0.5, edgecolor='k') plt.xlim(0, 100) # x 軸刻度范圍 plt.title('直方圖圖案填充示例') # 標題 plt.xlabel('x axis label') # x 軸標簽 plt.ylabel('y axis label') # y 軸標簽plt.show()【3x00】柱狀圖的繪制
【3x01】函數(shù)介紹 matplotlib.pyplot.bar()
matplotlib.pyplot.bar() 函數(shù)用于繪制柱狀圖。
基本語法:matplotlib.pyplot.bar(x, height[, width=0.8, bottom=None, align='center', \*\*kwargs])
基本參數(shù):
| x | 標量序列,每個矩形對應的 x 軸刻度 |
| height | 標量或標量序列,每個矩形對應的高度,即 y 軸刻度 |
| width | 標量或數(shù)組類型,每個矩形的寬度,默認為 0.8 |
| bottom | 標量或數(shù)組類型,y 軸的起始位置,默認為 0 |
| align | 矩形與 x 軸刻度對齊的位置,'center':中;'edge':左邊緣 |
其他參數(shù):
| color | 標量或數(shù)組類型,每個矩形的顏色,與 facecolor 作用相同,指定一個即可,如果兩者都指定,則取 facecolor 的值 |
| edgecolor | 標量或數(shù)組類型,柱狀圖邊緣線的顏色 |
| linewidth | 標量或數(shù)組類型,柱狀圖邊緣線的寬度,如果為0,則不繪制邊 |
| tick_label | 標量或數(shù)組類型,柱狀圖 x 軸的刻度標簽,默認使用數(shù)字標簽 |
| xerr / yerr | 標量,指定對應標準差(添加誤差線時會用到) |
| ecolor | 標量或數(shù)組類型,誤差線的線條顏色,默認值為 black |
| capsize | 標量,誤差線兩頭橫線的寬度,默認為 rcParams["errorbar.capsize"] = 0.0 |
| error_kw | 字典類型,可以此字典中定義 ecolor 和 capsize,比單獨指定的優(yōu)先級要高 |
| log | bool 值,y 坐標軸是否以指數(shù)刻度顯示 |
| alpha | float 類型,矩形透明度 |
| label | 圖例中顯示的標簽 |
| linestyle / ls | 線條樣式,此處指矩形邊緣線條樣式 '-' or 'solid', '--' or 'dashed', '-.' or 'dashdot' or ':' or 'dotted', 'none' or ' ' or '' |
| linewidth / lw | 線條寬度,此處指矩形邊緣線的寬度,float 類型,默認 0.8 |
| hatch | 矩形的填充圖案,可以是組合形式,如果有相同的圖案,則會增加填充的密度 取值可以是:'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*' |
【3x02】簡單柱狀圖示例
import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']x = [1, 2, 3, 4, 5] height = [5, 7, 4, 3, 1]# 設置 x 軸的標簽,也可以用 plt.xticks 方法來設置 tick_label = ['A', 'B', 'C', 'D', 'E'] # 設置顏色序列 color = ['red', 'yellow', 'peru', 'orchid', 'deepskyblue'] # 繪制柱狀圖,邊緣線寬度為1,顏色為黑色,樣式為 -- plt.bar(x, height, tick_label=tick_label, color=color, edgecolor='k', linewidth=1, linestyle='--')plt.title('簡單柱狀圖示例') plt.xlabel('x axis label') plt.ylabel('y axis label')plt.show()【3x03】添加與標準差的誤差線
首先定義一個列表,其中的元素是與每個值對應的標準差,ecolor 和 capsize 參數(shù)分別指定誤差線的顏色和兩頭橫線的寬度。這兩個參數(shù)可以通過 error_kw 字典形式組合起來。以字典形式的組合優(yōu)先級別要比單獨指定高。另外,柱狀圖指定標準差時要用 yerr,條形圖(橫向排列的柱狀圖)指定標準差時要用 xerr。
import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']x = [1, 2, 3, 4, 5] height = [5, 7, 4, 3, 2] std = [0.5, 0.1, 1.2, 0.3, 1.0] # 標準差tick_label = ['A', 'B', 'C', 'D', 'E'] # 設置 x 軸的標簽,也可以用 plt.xticks 方法來設置 color = ['red', 'yellow', 'peru', 'orchid', 'deepskyblue'] # 設置顏色序列 plt.bar(x,height,tick_label=tick_label,color=color,yerr=std, # 指定對應標準差# error_kw={# 'ecolor': 'k', # 指定誤差線的顏色# 'capsize': 6 # 指定誤差線兩頭橫線的寬度# },ecolor='k',capsize=6,edgecolor='k', # 指定邊緣線顏色linewidth=1 # 指定邊緣線寬度 )plt.title('柱狀圖添加誤差線示例') plt.xlabel('x axis label') plt.ylabel('y axis label')plt.show()【3x04】多序列柱狀圖
在繪制多序列的柱狀圖時,只需要多次調用 matplotlib.pyplot.bar() 函數(shù)即可,指定一個較小的寬度值(偏移量),繪制不同數(shù)據時設置不同的 x 位置刻度即可。
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']x = np.arange(5) height1 = np.array([5, 7, 4, 3, 2]) height2 = np.array([2, 4, 6, 7, 3]) height3 = np.array([3, 1, 7, 5, 2])# 設置寬度值(偏移量) width = 0.3 # 繪制不同數(shù)據時,x 軸依次增加一個偏移量 plt.bar(x, height1, width, label='bar1') plt.bar(x + width, height2, width, label='bar2') plt.bar(x + width * 2, height3, width, label='bar3')# 設置 x 軸刻度的標簽 plt.xticks(x + width, ['A', 'B', 'C', 'D', 'E']) plt.title('多序列柱狀圖示例') plt.xlabel('x axis label') plt.ylabel('y axis label') plt.legend()plt.show()【3x05】堆積的柱狀圖
所謂堆積圖,就是將多序列數(shù)據堆積到一個矩形上顯示,在柱狀圖中要實現(xiàn)堆積圖,只需要改變 bottom 參數(shù)即可,bottom 參數(shù)用于設置 y 軸基線,即柱狀圖的底邊在 y 軸上的起始刻度,第一條數(shù)據 data1 的基線可以設置為 0,即默認值,第二條數(shù)據 data2 的基線可以設置在 data1 的上方,即 bottom=data1,第三條數(shù)據 data3 的基線可以設置在 data1 + data2 的上方,即 bottom=data1+data2,以此類推。
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']x = np.arange(5) height1 = np.array([5, 7, 4, 3, 2]) height2 = np.array([2, 4, 6, 7, 3]) height3 = np.array([3, 1, 7, 5, 2])plt.bar(x, height1, label='bar1') plt.bar(x, height2, label='bar2', bottom=height1) plt.bar(x, height3, label='bar3', bottom=(height2+height1))plt.xticks(x, ['A', 'B', 'C', 'D', 'E']) plt.title('堆積的柱狀圖示例') plt.xlabel('x axis label') plt.ylabel('y axis label') plt.legend()plt.show()【3x06】填充其他樣式
hatch 參數(shù)可以讓柱狀圖的矩形填充其他樣式,可選值有:'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'。可以是不同圖案的組合形式,如果有相同的圖案,則會增加填充的密度。
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']x = np.arange(5) height1 = np.array([5, 7, 4, 3, 2]) height2 = np.array([2, 4, 6, 7, 3]) height3 = np.array([3, 1, 7, 5, 2])plt.bar(x, height1, label='bar1', color='w', hatch='///') plt.bar(x, height2, label='bar2', bottom=height1, color='w', hatch='xxx') plt.bar(x, height3, label='bar3', bottom=(height2+height1), color='w', hatch='|||')plt.xticks(x, ['A', 'B', 'C', 'D', 'E']) plt.title('柱狀圖圖案填充示例') plt.xlabel('x axis label') plt.ylabel('y axis label') plt.legend()plt.show()【3x07】添加文字描述
利用 matplotlib.pyplot.text() 方法可以在柱狀圖每個矩形上方添加文字描述。具體參數(shù)解釋可參考前面的文章:《Python 數(shù)據分析三劍客之 Matplotlib(二):文本描述 / 中文支持 / 畫布 / 網格等基本圖像屬性》
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']x = np.arange(5) height1 = np.array([5, 7, 4, 3, 2]) height2 = np.array([2, 4, 6, 7, 3]) height3 = np.array([3, 1, 7, 5, 2])width = 0.3 # 繪制不同數(shù)據時,x 軸依次增加一個偏移量 plt.bar(x, height1, width, label='bar1') plt.bar(x + width, height2, width, label='bar2') plt.bar(x + width * 2, height3, width, label='bar3')# 依次添加每條數(shù)據的標簽 for a, b in zip(x, height1):plt.text(a, b, b, ha='center', va='bottom') for c, d in zip(x, height2):plt.text(c + width, d, d, ha='center', va='bottom') for e, f in zip(x, height3):plt.text(e + width * 2, f, f, ha='center', va='bottom')# 設置 x 軸刻度的標簽 plt.xticks(x + width, ['A', 'B', 'C', 'D', 'E']) plt.title('柱狀圖添加文字描述示例') plt.xlabel('x axis label') plt.ylabel('y axis label') plt.legend()plt.show()這里是一段防爬蟲文本,請讀者忽略。 本文原創(chuàng)首發(fā)于 CSDN,作者 TRHX。 博客首頁:https://itrhx.blog.csdn.net/ 本文鏈接:https://itrhx.blog.csdn.net/article/details/105952856 未經授權,禁止轉載!惡意轉載,后果自負!尊重原創(chuàng),遠離剽竊!
【4x00】條形圖的繪制
【4x01】函數(shù)介紹 matplotlib.pyplot.barh()
matplotlib.pyplot.barh() 函數(shù)用于繪制條形圖(水平排列的柱狀圖)。
基本語法:matplotlib.pyplot.barh(y, width[, height=0.8, left=None, align='center', color, \*\*kwargs])
| y | 標量或數(shù)組類型,每個矩形對應的 y 軸刻度 |
| width | 標量或數(shù)組類型,每個矩形的寬度,即 x 軸刻度 |
| height | 標量序列,每個矩形的高度,默認 0.8 |
| left | 標量序列,每個矩形的左側 x 坐標的起始位置,默認值為 0 |
| align | 矩形的底邊與 y 軸刻度對齊的位置,'center':中;'edge':底邊 |
其他參數(shù):
| color | 標量或數(shù)組類型,每個矩形的顏色,與 facecolor 作用相同,指定一個即可,如果兩者都指定,則取 facecolor 的值 |
| edgecolor | 標量或數(shù)組類型,條形圖邊緣線的顏色 |
| linewidth | 標量或數(shù)組類型,條形圖邊緣線的寬度,如果為0,則不繪制邊 |
| tick_label | 標量或數(shù)組類型,條形圖 y 軸的刻度標簽,默認使用數(shù)字標簽 |
| xerr / yerr | 標量,指定對應標準差(添加誤差線時會用到) |
| ecolor | 標量或數(shù)組類型,誤差線的線條顏色,默認值為 black |
| capsize | 標量,誤差線兩頭橫線的寬度,默認為 rcParams["errorbar.capsize"] = 0.0 |
| error_kw | 字典類型,可以此字典中定義 ecolor 和 capsize,比單獨指定的優(yōu)先級要高 |
| log | bool 值,y 坐標軸是否以指數(shù)刻度顯示 |
| alpha | float 類型,矩形透明度 |
| label | 圖例中顯示的標簽 |
| linestyle / ls | 線條樣式,此處指矩形邊緣線條樣式 '-' or 'solid', '--' or 'dashed', '-.' or 'dashdot' or ':' or 'dotted', 'none' or ' ' or '' |
| linewidth / lw | 線條寬度,此處指矩形邊緣線的寬度,float 類型,默認 0.8 |
| hatch | 矩形的填充圖案,可以是組合形式,如果有相同的圖案,則會增加填充的密度 取值可以是:'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*' |
【4x02】簡單條形圖示例
import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']y = [1, 2, 3, 4, 5] width = [5, 7, 4, 3, 1]tick_label = ['A', 'B', 'C', 'D', 'E'] color = ['red', 'yellow', 'peru', 'orchid', 'deepskyblue'] plt.barh(y, width, tick_label=tick_label, color=color, edgecolor='k', linewidth=1, linestyle='--')plt.title('簡單條形圖示例') plt.xlabel('x axis label') plt.ylabel('y axis label')plt.show()【4x03】添加與標準差的誤差線
與柱狀圖一樣,首先定義一個列表,其中的元素是與每個值對應的標準差,ecolor 和 capsize 參數(shù)分別指定誤差線的顏色和兩頭橫線的寬度。這兩個參數(shù)可以通過 error_kw 字典形式組合起來。以字典形式的組合優(yōu)先級別要比單獨指定高。另外,柱狀圖指定標準差時要用 yerr,條形圖(橫向排列的柱狀圖)指定標準差時要用 xerr。
import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']y = [1, 2, 3, 4, 5] width = [5, 7, 4, 3, 2] std = [0.5, 0.1, 1.2, 0.3, 1.0] # 標準差tick_label = ['A', 'B', 'C', 'D', 'E'] # 設置 x 軸的標簽,也可以用 plt.xticks 方法來設置 color = ['red', 'yellow', 'peru', 'orchid', 'deepskyblue'] # 顏色序列 plt.barh(y,width,tick_label=tick_label,color=color,xerr=std, # 指定對應標準差# error_kw={# 'ecolor': 'k', # 指定誤差線的顏色# 'capsize': 6 # 指定誤差線兩頭橫線的寬度# },ecolor='k',capsize=6,edgecolor='k', # 指定邊緣線顏色linewidth=1 # 指定邊緣線寬度 )plt.title('條形圖添加誤差線示例') plt.xlabel('x axis label') plt.ylabel('y axis label')plt.show()【4x04】多序列條形圖
與多序列柱狀圖類似,在繪制多序列的條形圖時,只需要多次調用 matplotlib.pyplot.barh() 函數(shù)即可,指定一個較小的高度值(偏移量),繪制不同數(shù)據時設置不同的 y 位置刻度即可。
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']y = np.arange(5) width1 = np.array([5, 7, 4, 3, 2]) width2 = np.array([2, 4, 6, 7, 3]) width3 = np.array([3, 1, 7, 5, 2])# 設置高度值(偏移量) height = 0.3 # 繪制不同數(shù)據時,y 軸依次增加一個偏移量 plt.barh(y, width1, height, label='bar1') plt.barh(y + height, width2, height, label='bar2') plt.barh(y + height * 2, width3, height, label='bar3')# 設置 y 軸刻度的標簽 plt.yticks(y + height, ['A', 'B', 'C', 'D', 'E']) plt.title('多序列條形圖示例') plt.xlabel('x axis label') plt.ylabel('y axis label') plt.legend()plt.show()【4x05】堆積的條形圖
堆積圖就是將多序列數(shù)據堆積到一個矩形上顯示,和堆積的柱狀圖類似,在條形圖中要實現(xiàn)堆積圖,只需要改變 left 參數(shù)即可,left 參數(shù)用于設置 x 軸基線,即柱狀圖的底邊在 x 軸上的起始刻度,第一條數(shù)據 data1 的基線可以設置為 0,即默認值,第二條數(shù)據 data2 的基線可以設置在 data1 的上方,即 left=data1,第三條數(shù)據 data3 的基線可以設置在 data1 + data2 的上方,即 left=data1+data2,以此類推。
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']y = np.arange(5) width1 = np.array([5, 7, 4, 3, 2]) width2 = np.array([2, 4, 6, 7, 3]) width3 = np.array([3, 1, 7, 5, 2])plt.barh(y, width1, label='bar1') plt.barh(y, width2, label='bar2', left=width1) plt.barh(y, width3, label='bar3', left=(width1+width2))plt.yticks(y, ['A', 'B', 'C', 'D', 'E']) plt.title('堆積的條形圖示例') plt.xlabel('x axis label') plt.ylabel('y axis label') plt.legend()plt.show()【4x06】填充其他樣式
hatch 參數(shù)可以讓柱狀圖的矩形填充其他樣式,可選值有:'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'。可以是不同圖案的組合形式,如果有相同的圖案,則會增加填充的密度。
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']y = np.arange(5) width1 = np.array([5, 7, 4, 3, 2]) width2 = np.array([2, 4, 6, 7, 3]) width3 = np.array([3, 1, 7, 5, 2])plt.barh(y, width1, label='bar1', color='w', hatch='///') plt.barh(y, width2, label='bar2', left=width1, color='w', hatch='xxx') plt.barh(y, width3, label='bar3', left=(width1+width2), color='w', hatch='|||')plt.yticks(y, ['A', 'B', 'C', 'D', 'E']) plt.title('條形圖圖案填充示例') plt.xlabel('x axis label') plt.ylabel('y axis label') plt.legend()plt.show()【4x07】添加文字描述
利用 matplotlib.pyplot.text() 方法可以在條形圖每個矩形上方添加文字描述。具體參數(shù)解釋可參考前面的文章:《Python 數(shù)據分析三劍客之 Matplotlib(二):文本描述 / 中文支持 / 畫布 / 網格等基本圖像屬性》
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']y = np.arange(5) width1 = np.array([5, 7, 4, 3, 2]) width2 = np.array([2, 4, 6, 7, 3]) width3 = np.array([3, 1, 7, 5, 2])height = 0.3 # 繪制不同數(shù)據時,y 軸依次增加一個偏移量 plt.barh(y, width1, height, label='bar1') plt.barh(y + height, width2, height, label='bar2') plt.barh(y + height * 2, width3, height, label='bar3')# 依次添加每條數(shù)據的標簽 for a, b in zip(width1, y):plt.text(a, b-0.05, a) for c, d in zip(width2, y):plt.text(c, d+0.20, c) for e, f in zip(width3, y):plt.text(e, f+0.50, e)# 設置 y 軸刻度的標簽 plt.yticks(y + height, ['A', 'B', 'C', 'D', 'E']) plt.title('條形圖添加文字描述示例') plt.xlabel('x axis label') plt.ylabel('y axis label') plt.legend()plt.show()這里是一段防爬蟲文本,請讀者忽略。 本文原創(chuàng)首發(fā)于 CSDN,作者 TRHX。 博客首頁:https://itrhx.blog.csdn.net/ 本文鏈接:https://itrhx.blog.csdn.net/article/details/105952856 未經授權,禁止轉載!惡意轉載,后果自負!尊重原創(chuàng),遠離剽竊!
總結
以上是生活随笔為你收集整理的Python 数据分析三剑客之 Matplotlib(六):直方图 / 柱状图 / 条形图的绘制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 曝腾讯再裁员:至少缩减10% 微信、游戏
- 下一篇: Windows/Android/iOS