Để vẽ DataFrame Pandas thành biểu đồ tròn dùng 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.
- Tạo dataframe dữ liệu bảng hai chiều, kích thước có thể thay đổi, có thể hétérogène.
- Vẽ dataframe với activities index dùng phương thức pie().
- Để hiển thị figure, dùng phương thức show().
Ví dụ
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame({'activities': ['sleep', 'exercise', 'work', 'study'],
'hours': [8, 1, 9, 6]})
df.set_index('activities').plot.pie(y='hours', legend=False,
autopct='%1.1f%%')
plt.show()
Kết quả
