带有2个y轴的Seaborn箱线图 [英] Seaborn boxplot with 2 y-axes

查看:1220
本文介绍了带有2个y轴的Seaborn箱线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建带有2个y轴的海洋箱形图?由于规模不同,我需要这个。我当前的代码将覆盖箱图中的第一个箱,例如。

How can I create a seaborn boxplot with 2 y-axes? I need this because of different scales. My current code will overwrite the first box in the boxplot, eg. it is populated by 2 first data item from first ax and first item from second ax.

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

如何防止第一项被覆盖?

How do I prevent the first item getting overwritten?

编辑:

如果添加位置参数

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

我得到一个例外:

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

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

Probably because seaborn already sets that argument internally.

推荐答案

在这里使用seaborn可能没有太大意义。使用通常的matplotlib boxplots,可以按预期使用位置参数。

It may not make too much sense to use seaborn here. Using usual matplotlib boxplots allows you to use the positions argument as expected.

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()

这篇关于带有2个y轴的Seaborn箱线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆