Seaborn箱线图与2个y轴

3
我该如何创建一个带有两个y轴的seaborn箱线图?我需要这样做是因为两个数据的比例不同。我的当前代码会覆盖箱线图中的第一个箱子,例如,它将由第一个轴和第二个轴的第一个数据项中的2个数据填充。
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
import seaborn as sns

df = pd.DataFrame({'A': pd.Series(np.random.uniform(0,1,size=10)),
                   'B': pd.Series(np.random.uniform(10,20,size=10)),
                   'C': pd.Series(np.random.uniform(10,20,size=10))})

fig = plt.figure()
# 2/3 of  A4
fig.set_size_inches(7.8, 5.51)

plt.ylim(0.0, 1.1)

ax1 = fig.add_subplot(111)

ax1 = sns.boxplot(ax=ax1, data=df[['A']])

ax2 = ax1.twinx()

boxplot = sns.boxplot(ax=ax2, data=df[['B','C']])

fig = boxplot.get_figure()
fig

enter image description here

如何防止第一个项目被覆盖?

编辑:

如果我添加了positions参数

boxplot = sns.boxplot(ax=ax2, data=df[['B','C']], positions=[2,3])

我遇到了一个异常:

TypeError: boxplot() got multiple values for keyword argument 'positions'

可能是因为seaborn已经在内部设置了该参数。


您想在左侧绘制 A ,然后在右侧绘制 BC,这是您想要的吗? - ksai
没错。顺便说一下,我刚刚添加了一个编辑。 - beginner_
1个回答

5
可能在这里使用seaborn并没有太多意义。使用常规的matplotlib箱线图,你可以像预期的那样使用positions参数。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')

df = pd.DataFrame({'A': pd.Series(np.random.uniform(0,1,size=10)),
                   'B': pd.Series(np.random.uniform(10,20,size=10)),
                   'C': pd.Series(np.random.uniform(10,20,size=10))})

fig, ax1  = plt.subplots(figsize=(7.8, 5.51))

props = dict(widths=0.7,patch_artist=True, medianprops=dict(color="gold"))
box1=ax1.boxplot(df['A'].values, positions=[0], **props)

ax2 = ax1.twinx()
box2=ax2.boxplot(df[['B','C']].values,positions=[1,2], **props)

ax1.set_xlim(-0.5,2.5)
ax1.set_xticks(range(len(df.columns)))
ax1.set_xticklabels(df.columns)

for b in box1["boxes"]+box2["boxes"]:
    b.set_facecolor(next(ax1._get_lines.prop_cycler)["color"])
plt.show()

enter image description here


你可以将 positions 参数传递给 seaborn.boxplot 吗? - Paul H
@PaulH 嗯,不是的。根据问题,这会导致 TypeError: boxplot() got multiple values for keyword argument 'positions' - ImportanceOfBeingErnest
@PaulH 的确原因是因为它在 seaborn 代码中被硬编码了。 (https://github.com/mwaskom/seaborn/blob/0beede57152ce80ce1d4ef5d0c0f1cb61d118375/seaborn/categorical.py#L479) - ImportanceOfBeingErnest

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接