python之 matplotlib模塊之繪制堆疊柱狀圖


我們先來看一個結果圖

看到這個圖,我個人的思路是

1 設置標題

import numpy as np
import matplotlib.pyplot as plt

plt.title('Scores by group and gender')

2 x坐標的間隔設置和文字設置

N = 13
ind = np.arange(N)  #[ 0  1  2  3  4  5  6  7  8  9 10 11 12]
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8', 'G9', 'G10', 'G11', 'G12', 'G13'))

3 y坐標的文字設置和間隔設置

plt.yticks(np.arange(0, 81, 20)) #0到81 間隔20
plt.ylabel('Scores')

4 開始繪制主題條形圖

Bottom = (52, 49, 48, 47, 44, 43, 41, 41, 40, 38, 36, 31, 29)
Center = (38, 40, 45, 42, 48, 51, 53, 54, 57, 59, 57, 64, 62)
Top = (10, 11, 7, 11, 8, 6, 6, 5, 3, 3, 7, 5, 9)

d = []
for i in range(0, len(Bottom)):
    sum = Bottom[i] + Center[i]
    d.append(sum)

width = 0.35  # 設置條形圖一個長條的寬度

p1 = plt.bar(ind, Bottom, width, color='blue')  
p2 = plt.bar(ind, Center, width, bottom=Bottom,color='green')  #在p1的基礎上繪制,底部數據就是p1的數據
p3 = plt.bar(ind, Top, width, bottom=d,color='red')    #在p1和p2的基礎上繪制,底部數據就是p1和p2

5 設置legend區分三部分數據

plt.legend((p1[0], p2[0], p3[0]), ('Bottom', 'Center', 'Top'),loc = 3)  #loc=3 表示lower left 也就是底部最左

loc的設置參數

'best'         : 0, (only implemented for axes legends)(自適應方式)
'upper right'  : 1,
'upper left'   : 2,
'lower left'   : 3,
'lower right'  : 4,
'right'        : 5,
'center left'  : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center'       : 10,

6 繪制出圖形

plt.show()

7 最終代碼為:

import numpy as np
import matplotlib.pyplot as plt

plt.title('Scores by group and gender')

N = 13
ind = np.arange(N)  #[ 0  1  2  3  4  5  6  7  8  9 10 11 12]
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8', 'G9', 'G10', 'G11', 'G12', 'G13'))

plt.ylabel('Scores')
plt.yticks(np.arange(0, 81, 20))

Bottom = (52, 49, 48, 47, 44, 43, 41, 41, 40, 38, 36, 31, 29)
Center = (38, 40, 45, 42, 48, 51, 53, 54, 57, 59, 57, 64, 62)
Top = (10, 11, 7, 11, 8, 6, 6, 5, 3, 3, 7, 5, 9)

d = []
for i in range(0, len(Bottom)):
    sum = Bottom[i] + Center[i]
    d.append(sum)

width = 0.35  # 設置條形圖一個長條的寬度
p1 = plt.bar(ind, Bottom, width, color='blue') 
p2 = plt.bar(ind, Center, width, bottom=Bottom,color='green')  
p3 = plt.bar(ind, Top, width, bottom=d,color='red')

plt.legend((p1[0], p2[0], p3[0]), ('Bottom', 'Center', 'Top'),loc = 3)

plt.show()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM