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

Tùy chỉnh chú thích (annotation) với Seaborn FacetGrid

Để tùy chỉnh tiêu đề cho từng facet trong sns.FacetGrid, dùng g.set_titles() sau khi map hàm vẽ.

Các bước

  • Thiết lập figure size và autolayout.
  • Tạo DataFrame với cột phân nhóm (col2) và giá trị (col1).
  • Tạo FacetGrid: sns.FacetGrid(data=df, col='col2', height=3.5).
  • Map histogram: g.map(plt.hist, 'col1', color='red', lw=0).
  • Đặt tiêu đề facet: g.set_titles('{col_name}').
  • Hiển thị bằng show().

Ví dụ

import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

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

df = pd.DataFrame({'col1': [3, 7, 8, 1], 'col2': ["three", "seven", "one", "zero"]})
g = sns.FacetGrid(data=df, col='col2', height=3.5)
g.map(plt.hist, 'col1', color='red', lw=0)
g.set_titles('{col_name}')
plt.show()

Kết quả

Tùy chỉnh chú thích (annotation) với Seaborn FacetGrid