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

Cách xác định thứ tự cột trong biểu đồ cột matplotlib?

Để xác định thứ tự cột trong bar chart matplotlib, thực hiện:

  • Thiết lập kích thước hình và padding.
  • Tạo dataframe df dữ liệu 2D.
  • Thêm subplot vào figure hiện tại.
  • Vẽ bar plot với df.
  • Thêm subplot khác.
  • Tạo df_sorted sắp xếp theo cột marks.
  • Vẽ bar plot với df_sorted.
  • Hiển thị bằng show().

Ví dụ

import pandas as pd
from matplotlib import pyplot as plt

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

df = pd.DataFrame(dict(
    names=['John', 'James', 'David', 'Gary', 'Watson'],
    marks=[23, 34, 30, 19, 20]
))

plt.subplot(121)
plt.bar('names', 'marks', data=df, color='green')

plt.subplot(122)
df_sorted = df.sort_values('marks')
plt.bar('names', 'marks', data=df_sorted, color='blue')

plt.show()

Đầu ra

Sẽ tạo ra đầu ra:

Cách xác định thứ tự cột trong biểu đồ cột matplotlib?
Cách xác định thứ tự cột trong biểu đồ cột matplotlib?