Boxplot:seaborn 中的自定义宽度

2023-12-31

我正在尝试在seaborn中绘制箱线图,其宽度取决于x轴值的对数。我正在创建宽度列表并将其传递给 seaborn.boxplot 的 widths=widths 参数。

但是,我得到了

raise ValueError(datashape_message.format("widths"))
ValueError: List of boxplot statistics and `widths` values must have same the length

当我调试和检查时,箱线图统计中只有一个字典,而我有 8 个箱线图。 无法准确判断问题出在哪里。

我使用 pandas 数据框和seaborn 进行绘图。


Seaborn 的箱线图似乎不理解widths=范围。

这是一种创建箱线图的方法x通过 matplotlib 的值boxplot它确实接受width=范围。下面的代码假设数据是在 panda 的数据框中组织的。

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

df = pd.DataFrame({'x': np.random.choice([1, 3, 5, 8, 10, 30, 50, 100], 500),
                   'y': np.random.normal(750, 20, 500)})
xvals = np.unique(df.x)
positions = range(len(xvals))
plt.boxplot([df[df.x == xi].y for xi in xvals],
            positions=positions, showfliers=False,
            boxprops={'facecolor': 'none'}, medianprops={'color': 'black'}, patch_artist=True,
            widths=[0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
means = [np.mean(df[df.x == xi].y) for xi in xvals]
plt.plot(positions, means, '--k*', lw=2)
# plt.xticks(positions, xvals) # not needed anymore, as the xticks are set by the swarmplot
sns.swarmplot('x', 'y', data=df)
plt.show()

一个相关的问题询问如何根据组大小设置框的宽度。宽度可以计算为某个最大宽度乘以每个组的大小与最大组的大小相比。

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

y_true = np.random.normal(size=100)
y_pred = y_true + np.random.normal(size=100)
df = pd.DataFrame({'y_true': y_true, 'y_pred': y_pred})
df['y_true_bin'] = pd.cut(df['y_true'], range(-3, 4))

sns.set()
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 5))
sns.boxplot(x='y_true_bin', y='y_pred', data=df, color='lightblue', ax=ax1)

bins, groups = zip(*df.groupby('y_true_bin')['y_pred'])
lengths = np.array([len(group) for group in groups])
max_width = 0.8
ax2.boxplot(groups, widths=max_width * lengths / lengths.max(),
            patch_artist=True, boxprops={'facecolor': 'lightblue'})
ax2.set_xticklabels(bins)
ax2.set_xlabel('y_true_bin')
ax2.set_ylabel('y_pred')
plt.tight_layout()
plt.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Boxplot:seaborn 中的自定义宽度 的相关文章