twinx和sns.barplot seaborn是重叠的酒吧

时间:2018-01-10 06:45:25

标签: python matplotlib seaborn

我想使用sns.seaborn在2个不同的轴上显示np.sumnp.mean(我假设为ax2 = ax1.twinx())。我的探索是图形重叠且不可读。

我是否正确接近了这个问题? 我该怎么做才能让这些酒吧彼此相邻?

import seaborn as sns
tips = sns.load_dataset("tips")
f, ax1 = plt.subplots()
ax2 = ax1.twinx()
sns.barplot(x="day", y="total_bill", data=tips, estimator=np.mean, ax=ax1)
sns.barplot(x="day", y="total_bill", data=tips, estimator=np.sum, ax=ax2, ci=None)

感谢您的帮助

拉​​里

1 个答案:

答案 0 :(得分:2)

您可能最好使用pandas汇总数据,然后使用标准的matplotlib ax.bar()函数绘制结果数据框。

如果你坚持使用seaborn,以下是获得所需结果的某种“hackish”方式。

为了将每个条略微向左或向右移动,我创建了一个我用于色调嵌套的虚拟分类列,并使用hue_order=参数请求其中一个图是在左边,第二个条形图的反向顺序在右边。

# create a dummy categorical column with only one category
invoicedb.loc[:,'dummy'] = 'dummy'

f, ax1 = plt.subplots()
ax2 = ax1.twinx()
sns.barplot(x="InvoiceMonth", y="TotalInvoice", hue='dummy', data=invoicedb, estimator = np.mean, ax = ax1, color = 'r', hue_order=['dummy','other'])
sns.barplot(x="InvoiceMonth", y="TotalInvoice", hue='dummy', data=invoicedb, estimator = np.sum, ci = None, ax = ax2, color = 'b', hue_order=['other','dummy'])
# hue-nesting automatically creates a legend that we need to remove by hand
ax1.legend_.remove()
ax2.legend_.remove()