在 matplotlib 3.5 中,盒子存储在ax.patches
代替ax.artists
.
在 Seaborn 中更改颜色的推荐方法是将数据帧转换为长表 https://seaborn.pydata.org/tutorial/data_structure.html#long-form-vs-wide-form-data通过熊猫'melt() https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html然后使用hue=
在同一个变量上x=
和...一起palette=
. (palette
其中可以是字典或颜色列表。)
通过临时更改列名称,将自动设置 x 刻度标签。如果ax
已预先创建,将其作为参数传递告诉seaborn绘制到该斧头上。 (轴级 https://seaborn.pydata.org/tutorial/function_overview.html#figure-level-vs-axes-level-functions函数返回ax
情节创建于其上;当。。。的时候ax
作为参数给出,不需要存储返回值。)
这是一个例子:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
random_df = pd.DataFrame(data={'0': np.random.rand(10),
'1': np.random.rand(10),
'2': np.random.rand(10),
'3': np.random.rand(10),
'4': np.random.rand(10)})
sns.set(style='whitegrid')
fig, ax = plt.subplots(figsize=(12, 9))
xvalues = ["Label 1", "Label 2", "Label 3", "Label 4", "Label 5"]
palette = ['plum', 'g', 'orange', 'b', 'r']
melted_df = random_df.set_axis(xvalues, axis=1).melt(var_name='Variable', value_name='Accuracy')
sns.boxplot(data=melted_df, x='Variable', y='Accuracy', hue='Variable', palette=palette,
width=0.7, dodge=False, ax=ax)
ax.legend_.remove() # remove the legend, as the information is already present in the x labels
ax.set_xlabel('') # remove unuseful xlabel ('Variable')
ax.set_ylabel("Accuracy", fontsize=14)
sns.despine(top=True, right=True, left=True, bottom=False)
plt.show()