twinx 和 sns.barplot seaborn 是重叠的条形 [英] twinx and sns.barplot seaborn are overlapping bars

查看:32
本文介绍了twinx 和 sns.barplot seaborn 是重叠的条形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 sns.seaborn 在2个不同的轴上显示 np.sum np.mean (对于<代码>ax2 = ax1.twinx() 我假设).我的问题是图表重叠且不可读.

I would like to use sns.seaborn to display the np.sum and the np.mean on 2 different axes (with ax2 = ax1.twinx() I assume). The probem I have is that the graphs are overlapped and not readable.

我正确地解决了这个问题吗?我该怎么做才能使那些酒吧彼此相邻?

Am I approaching the problem correctly? What can I do to get those bars next to each other?

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)

感谢您的帮助

拉里

推荐答案

你最好先用 pandas 聚合你的数据,然后使用标准的 matplotlib ax.bar()code> 函数来绘制结果数据框.

You might be better off aggregating your data with pandas and then using the standard matplotlib ax.bar() function to plot the resulting dataframe.

如果您坚持使用seaborn,则以下内容是获得预期结果的一种骇人听闻"的方式.

If you insist on using seaborn, the following is somewhat of a "hackish" way of obtaining the desired result.

要将每个小节稍微向左或向右移动,我创建了一个用于分类色调的虚拟分类列,并使用 hue_order = 参数请求其中一个该图位于左侧,而第二个条形图则位于相反的顺序.

To move each bars slightly to the left or to the right, I create a dummy categorical column that I'm using for hue-nesting, and I use the hue_order= parameter to request one of the plot to be on the left, and the reverse order for the second bar-plot to be on the right.

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

这篇关于twinx 和 sns.barplot seaborn 是重叠的条形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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