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

Vẽ biểu đồ tròn lồng nhau (nested pie chart) trong Matplotlib


Các bước

  1. Thiết lập kích thước hình và padding.
  2. Tạo figure và subplots.
  3. Khởi tạo biến size, tạo dữ liệu vals, cmap, outer_colors, inner_colors bằng numpy.
  4. Dùng pie() để vẽ biểu đồ tròn ngoài và trong.
  5. Gọi 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

fig, ax = plt.subplots()
size = 0.3
vals = np.array([[60., 32.], [37., 40.], [29., 10.]])
cmap = plt.get_cmap("tab20c")
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap([1, 2, 5, 6, 9, 10])

ax.pie(vals.sum(axis=1), radius=1, colors=outer_colors,
       wedgeprops=dict(width=size, edgecolor='w'))
ax.pie(vals.flatten(), radius=1-size, colors=inner_colors,
       wedgeprops=dict(width=size, edgecolor='w'))
plt.show()

Kết quả

Vẽ biểu đồ tròn lồng nhau (nested pie chart) trong Matplotlib