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

Tự động xoay màu (color cycle) cho bar plot Matplotlib

Để bar plot tự động chuyển màu qua chu kỳ màu tùy chỉnh, thiết lập plt.rc('axes', prop_cycle=plt.cycler('color', ['r','g','b','y'])).

Các bước

  • Thiết lập figure size và autolayout.
  • Đặt cycler màu cho axes.
  • Tạo DataFrame nhiều cột số.
  • Vẽ bar chart: df.set_index('name').plot(kind='bar').
  • Hiển thị bằng show().

Ví dụ

import matplotlib.pyplot as plt
import pandas as pd

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

plt.rc('axes', prop_cycle=(plt.cycler('color', ['r', 'g', 'b', 'y'])))
df = pd.DataFrame(dict(name=["John", "Jacks", "James"], age=[23, 20, 26], marks=[88, 90, 76], salary=[90, 89, 98]))
df.set_index('name').plot(kind='bar')
plt.show()

Kết quả

Tự động xoay màu (color cycle) cho bar plot Matplotlib