第一章 使用 matplotlib 繪制折線圖
第二章 使用 matplotlib 繪制條形圖
第三章 使用 matplotlib 繪制直方圖
第四章 使用 matplotlib 繪制散點(diǎn)圖
第五章 使用 matplotlib 繪制餅圖
第六章 使用 matplotlib 繪制熱力圖
第七章 使用 matplotlib 繪制堆疊條形圖
第八章 使用 matplotlib 在一個(gè)畫布內(nèi)繪制多個(gè)圖
上一章我們講述了熱力圖的繪制,本章我們來講述堆疊條形圖的繪制。
堆疊條形圖是一種用來分解整體、比較各部分的圖。與條形圖類似,堆疊條形圖常被用于比較不同類別的數(shù)值。而且,它的每一類數(shù)值內(nèi)部,又被劃分為多個(gè)子類別,這些子類別一般用不同的顏色來表示。
如果說條形圖可以幫助我們觀察總量,那么堆疊條形圖則可以同時(shí)反映總量與結(jié)構(gòu),即總量是多少?它又是由哪些部分構(gòu)成的?進(jìn)而,我們還可以探究哪一部分比例最大,以及每一部分的變動(dòng)情況等等。
堆疊條形圖的繪制和條形圖類似,同樣是調(diào)用 bar 函數(shù),只不過在參數(shù)設(shè)置時(shí)稍有區(qū)別,示例代碼如下:
# importing package import matplotlib.pyplot as plt import numpy as np plt.style.use('fivethirtyeight') x = ['A', 'B', 'C', 'D'] y1 = np.array([10, 20, 10, 30]) y2 = np.array([20, 25, 15, 25]) y3 = np.array([12, 15, 19, 6]) y4 = np.array([10, 29, 13, 19]) plt.bar(x, y1, label='Round1', width=0.67) plt.bar(x, y2, bottom=y1, label='Round2', width=0.67) plt.bar(x, y3, bottom=y1+y2, label='Round3', width=0.67) plt.bar(x, y4, bottom=y1+y2+y3, label='Round4', width=0.67) plt.xlabel("Teams") plt.ylabel("Score") plt.legend() plt.title("Scores by Teams in 4 Rounds") plt.tight_layout() plt.show()
在上面的代碼中,列表 x 代表 4 只隊(duì)伍,列表 y1、y2、y3 和 y4 分別表示 4 只隊(duì)伍在 4 局比賽的得分。在進(jìn)行圖形繪制時(shí),在繪制 y2 數(shù)據(jù)時(shí),設(shè)置 bottom = y1,意思是在 y1 數(shù)據(jù)繪制的條形圖的基礎(chǔ)進(jìn)行繪制,也就是形成堆疊圖。代碼執(zhí)行完得到的圖形如下圖所示:
import matplotlib.pyplot as plt import numpy as np plt.style.use('fivethirtyeight') x = ['A', 'B', 'C', 'D'] y1 = np.array([10, 20, 10, 30]) y2 = np.array([20, 25, 15, 25]) y3 = np.array([12, 15, 19, 6]) y4 = np.array([10, 29, 13, 19]) plt.barh(x, y1, label='Round1', height=0.67) plt.barh(x, y2, left=y1, label='Round2', height=0.67) plt.barh(x, y3, left=y1+y2, label='Round3', height=0.67) plt.barh(x, y4, left=y1+y2+y3, label='Round4', height=0.67) plt.xlabel("Score") plt.ylabel("Teams") plt.legend() plt.title("Scores by Teams in 4 Rounds") plt.tight_layout() plt.show()
在繪制水平方向的堆疊條形圖時(shí),需要將參數(shù) bottom 改為 left,將參數(shù) width 改為 height,需要將 x 軸標(biāo)簽改為 Score,y 軸標(biāo)簽改為 Teams。其他的和垂直方向的堆疊條形圖的繪制類似。代碼執(zhí)行后得到的圖形如下圖所示:
import matplotlib.pyplot as plt import numpy as np plt.style.use('fivethirtyeight') x = ['A', 'B', 'C', 'D'] y1 = np.array([10, 20, 10, 30]) y2 = np.array([20, 25, 15, 25]) y3 = np.array([12, 15, 19, 6]) y4 = np.array([10, 29, 13, 19]) plt.barh(x, y1, label='Round1', height=0.67) plt.barh(x, y2, left=y1, label='Round2', height=0.67) plt.barh(x, y3, left=y1+y2, label='Round3', height=0.67) plt.barh(x, y4, left=y1+y2+y3, label='Round4', height=0.67) plt.xlabel("Score") plt.ylabel("Teams") plt.legend(loc='lower right') plt.title("Scores by Teams in 4 Rounds") plt.tight_layout() plt.show()
在上面的代碼中,我們通過設(shè)置 legend 函數(shù)的 loc 參數(shù)來改變圖例的位置。
對(duì)比不同類別數(shù)據(jù)的數(shù)值大小,同時(shí)對(duì)比每一類別數(shù)據(jù)中,子類別的構(gòu)成及大小。
本章我們講了堆疊條形圖的繪制以及堆疊條形圖的適用場(chǎng)景和不適用場(chǎng)景。
聯(lián)系客服