我在seaborn中为箱线图编写了代码,我想标记箱线图的平均值,而不是showmeans选项,即“数字”。
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import matplotlib
import math
data = {
'GROUP': ['AAA1', 'AAA1', 'AAA1', 'AAA1'],
'NAME': [1, 2, 3, 4],
'QTY': [56, 43, 55, 59],
'TEM0001': ['A52', 'B52', 'A22', 'A22'],
'TEM0002': ['B52', 'C32', 'B56', 'B56'],
'TEM0003': ['C52', 'D54', 'C32', 'C4'],
'TEM0004': ['D54', 'E43', 'D33', 'D33'],
'TEM0005': ['E43', 'T56', 'E44', 'E44'],
}
df = pd.DataFrame(data)
df
column_indices = range(3,10)
fig, axes = plt.subplots(math.ceil( len(column_indices)/4), 4, figsize=(10,8))
axes = axes.flatten()
for i, col_idx in enumerate(column_indices):
df_selected = df.iloc[:, [2, col_idx]]
bp = sns.boxplot(data=df_selected, x=df_selected.columns[1], y='QTY', hue=df_selected.columns[1], ax=axes[i])
m1= df_selected.groupby(df_selected.columns[1])['QTY'].median().values
for j in range(len(column_indices), len(axes)):
axes[j].axis('off')
plt.tight_layout()
plt.show()
为每个箱线图标记平均值。
只需添加标签参数,具体方法如下:
bp = sns.boxplot(data=df_selected, x=df_selected.columns[1], y='QTY', hue=df_selected.columns[1], ax=axes[i], label="your_label")
然后在显示箱线图之前添加图例方法:
plt.tight_layout()
# add .legend() method
plt.legend()
plt.show()