Để tô màu Seaborn boxplot dựa trên tên cột dataframe, 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 Pandas dataframe với hai cột: col1 và col2.
- Vẽ boxplot với orientation ngang.
- Lấy các artist boxes.
- Lặp qua boxes và đặt facecolor cho box.
- Để hiển thị figure, dùng phương thức show().
Ví dụ
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame(
[[2, 4],
[7, 2]],
columns=['col1', 'col2'])
ax = sns.boxplot(data=df, orient='h')
boxes = ax.artists
for i, box in enumerate(boxes):
if 'col1' in df.columns[i]:
box.set_facecolor('r')
else:
box.set_facecolor('b')
plt.show()
Kết quả
