我想使用seaborn 创建一个简单的箱线图。但是,我希望各组的顺序不同。我发现可以将可选的
ordering
参数传递给箱线图调用来执行此操作。然而,对我来说,这会产生一个内部 seaborn 错误,这似乎是一个错误。我在任何地方都找不到任何对该错误的引用。附件是一个最小的可重现示例:
import seaborn as sns
import matplotlib.pyplot as plt
dataset = {
'X': [1, 2, 1, 2, 3, 2, 1, 3],
'Y': [10, 15, 8, 12, 14, 11, 9, 13],
'group': ['A', 'B', 'A', 'B', 'C', 'B', 'A', 'C']
}
fig, ax = plt.subplots()
order = ['A', 'B', 'C']
sns.boxplot(x='X', y='Y', hue='group', data=dataset, ordering=order, ax=ax)
plt.show()
错误是
UnboundLocalError: local variable 'boxprops' referenced before assignment
来自
seaborn/categorical.py", line 736, in plot_boxes
self._configure_legend(ax, legend_artist, boxprops)
我使用的是 Seaborn 版本 0.13.0。我已尝试降级到 0.12.0,但订购功能似乎还不存在。
我是否应用了错误的顺序?或者这只是库中的一个错误?如果是这样,我该如何解决?
seaborn
ordering
上没有财产boxplot
。请考虑参数 order
或 hue_order
,或对数据进行排序以达到您的意图。如果您仍然想要结果,下面的代码会生成色调顺序为 ['C', 'A', 'B']
的后续图像。
代码:
import seaborn as sns
import matplotlib.pyplot as plt
dataset = {
'X': [1, 2, 1, 2, 3, 2, 1, 3],
'Y': [10, 15, 8, 12, 14, 11, 9, 13],
'group': ['A', 'B', 'A', 'B', 'C', 'B', 'A', 'C']
}
fig, ax = plt.subplots()
order = ['C', 'A', 'B'] # Specify the desired order of groups
sns.boxplot(x='X', y='Y', hue='group', hue_order=order, data=dataset, ax=ax) # Use 'hue_order' instead of 'ordering'
plt.show()
图片: