【问题标题】:Seaborn boxplot with 2 y-axes带有 2 个 y 轴的 Seaborn 箱线图
【发布时间】:2023-03-10 21:01:01
【问题描述】:

如何创建带有 2 个 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

如何防止第一项被覆盖?

编辑:

如果我添加位置参数

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

我得到一个例外:

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

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

【问题讨论】:

  • 您想在左侧绘制A,然后在右侧绘制B,然后在右侧绘制C。是不是你想要的?
  • 没错。仅供参考,我刚刚添加了一个编辑。

标签: python matplotlib seaborn boxplot


【解决方案1】:

在这里使用 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()

【讨论】:

  • 你能把positions传给seaborn.boxplot吗?
  • @PaulH 好吧,不。根据问题,这导致TypeError: boxplot() got multiple values for keyword argument 'positions'
  • @PaulH 原因确实是hardcoded in the seaborn code
猜你喜欢
  • 2023-04-07
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-16
  • 2012-08-18
相关资源
最近更新 更多