Python數據可視化第 5 講:matplotlib繪製條形圖函數bar

1. bar 函數介紹

bar 函數用於繪製條形圖,每個條按給定的對齊方式定位在參數 x 指定的位置。它們的寬、高尺寸由參數 height 和 width 決定。垂直基線由參數 bottom 指定,默認爲0。函數的調用格式如下:

bar(x, height, width, bottom, **kwargs)
bar(x, height, **kwargs)
bar(x, height)

參數說明:

  • x:標量序列,每個條定位在 x 指定的位置。
  • height:標量或標量序列,條形圖的高度。
  • width:標量或類似數組,可選,條形圖的寬度(默認值:0.8)。
  • bottom:標量或類似數組,可選,條形圖底部的y座標(默認值:0)。
  • align:對齊方式,可選,默認值:“center”。 “center”:將條形圖置於x位置的中心;“edge”:將條的左邊緣與x位置對齊。

2. bar 函數繪圖示例

2.1 繪製一個基本的條形圖

繪製一個具有4個條的條形圖,代碼如下:

import matplotlib.pyplot as plt

# step1:準備畫圖的數據
x = [1, 2, 3, 4]
height = [12, 34, 25, 30]
# step2:手動創建一個figure對象,相當於一個空白的畫布
figure = plt.figure()
# step3:在畫布上添加1個子塊,標定繪圖位置
axes1 = plt.subplot(1, 1, 1)
# step4:繪製條形圖
axes1.bar(x, height)
axes1.set_title('bar example')

# step5:展示
plt.show()

上面代碼的運行結果:

2.2 繪製條形圖並設置基本屬性

繪製一個具有4個條的條形圖,並設置基本屬性,代碼如下:

import matplotlib.pyplot as plt

# step1:準備畫圖的數據
x = [1, 2, 3, 4]
height = [12, 34, 25, 30]
# step2:手動創建一個figure對象,相當於一個空白的畫布
figure = plt.figure()
# step3:在畫布上添加1個子塊,標定繪圖位置
axes1 = plt.subplot(1, 1, 1)
# step4:繪製條形圖
axes1.bar(x, height, width=0.5)
# step5:條形圖基本屬性設置
axes1.set_title('GDP of 2019')
axes1.set_ylabel('trillion dollars')
plt.xticks(x, ('spring', 'summer', 'autumn', 'winter'))
# step6:展示
plt.show()

上面代碼的運行結果:

2.3 繪製複合條形圖

繪製複合條形圖,並設置基本屬性,代碼示例如下:

import matplotlib.pyplot as plt
import numpy as np

# step1:準備畫圖的數據
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
x = np.arange(len(labels))  # 條形圖x軸座標
width = 0.35  # 條形圖寬度

# step2:手動創建一個figure對象,即一張空白的畫布
figure = plt.figure()
# step3:在畫布上添加1個子塊,標定繪圖位置
axes1 = plt.subplot(1, 1, 1)
# step4:繪製條形圖
axes1.bar(x - width / 2, men_means, width, label='Men')
axes1.bar(x + width / 2, women_means, width, label='Women')
# step5:條形圖基本屬性設置
# Add some text for labels, title and custom x-axis tick labels, etc.
axes1.set_ylabel('Scores')
axes1.set_title('Scores by group and gender')
axes1.set_xticks(x)
axes1.set_xticklabels(labels)
axes1.legend()
# step6:展示
plt.show()

上面代碼的運行結果:

2.4 堆積式條形圖繪製

採用“堆積”的方式繪製條形圖,形成漸變色效果,並在條形圖中添加一個表格,設置基本屬性,代碼示例如下:

import numpy as np
import matplotlib.pyplot as plt

# step1:準備畫圖的數據
data = [[66386, 174296, 75131, 577908, 32015],
        [58230, 381139, 78045, 99308, 160454],
        [89135, 80552, 152558, 497981, 603535],
        [78415, 81858, 150656, 193263, 69638],
        [139361, 331509, 343164, 781380, 52269]]
columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
rows = ['%d year' % x for x in (100, 50, 20, 10, 5)]
values = np.arange(0, 2500, 500)
value_increment = 1000

# 生成一組顏色,用於條形圖顏色設置,形成漸變效果
colors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)))
n_rows = len(data)

# 條形圖x軸位置和寬度
index = np.arange(len(columns)) + 0.3
bar_width = 0.4

# 初始化堆積條形圖的垂直偏移
y_offset = np.zeros(len(columns))

# 打條形圖併爲表格創建文本標籤
cell_text = []
# 手動創建一個figure對象,相當於一個空白的畫布
figure = plt.figure()
# 在畫布上增加一個子塊
axes1 = figure.add_subplot(1, 1, 1)
# 循環,堆積式繪圖,形成漸變色效果
for row in range(n_rows):
    axes1.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row])
    y_offset = y_offset + data[row]
    cell_text.append(['%1.1f' % (x / 1000.0) for x in y_offset])
# 反轉顏色和文本標籤以在頂部顯示最後一個值
colors = colors[::-1]
cell_text.reverse()

# 在座標系的底部增加一張表
the_table = axes1.table(cellText=cell_text,
                        rowLabels=rows,
                        rowColours=colors,
                        colLabels=columns,
                        loc='bottom')

# 調整子塊佈局,爲表格騰出空間
plt.subplots_adjust(left=0.2, bottom=0.2)

# 基本設置
plt.ylabel("Loss in ${0}'s".format(value_increment))
plt.yticks(values * value_increment, ['%d' % val for val in values])
plt.xticks([])
plt.title('Loss by Disaster')

# 繪圖
plt.show()

上面代碼的運行結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章