Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách tạo Diverging Stacked Bar Chart trong Matplotlib?


Để tạo Diverging Stacked Bar Chart trong Matplotlib, chúng ta có thể thực hiện các bước sau:

  • Thiết lập kích thước figure và điều chỉnh padding giữa và xung quanh subplots.
  • Khởi tạo biến N để lấy số chỉ số.
  • Lấy menMeans, womenMeans, menStd và womenStd tuple.
  • Khởi tạo width của các cột.
  • Tạo figure và tập subplots.
  • Để có diverging bar, ta đặt dữ liệu với giá trị dương và âm để tạo cột phân kỳ.
  • Thêm đường ngang qua trục.
  • Đặt Ylabel, title, ticks, ticklabels và legend.
  • Để hiển thị figure, dùng phương thức show().

Ví dụ

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

N = 5
menMeans = (20, -35, 30, 35, -27)
womenMeans = (25, -32, 34, 20, -25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)

ind = np.arange(N)
width = 0.35

fig, ax = plt.subplots()
p1 = ax.bar(ind, menMeans, width, yerr=menStd, label='Men')
p2 = ax.bar(ind, womenMeans, width, bottom=menMeans, yerr=womenStd, label='Women')

ax.axhline(0, color='grey', linewidth=0.8)
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend()

plt.show()

Kết quả

Cách tạo Diverging Stacked Bar Chart trong Matplotlib?