简体   繁体   English

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

[英]twinx and sns.barplot seaborn are overlapping bars

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). 我想用sns.seaborn显示np.sumnp.mean 2个不同的轴线(与ax2 = ax1.twinx()我假定)。 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)

Thanks for your help 谢谢你的帮助

Larry 拉里

You might be better off aggregating your data with pandas and then using the standard matplotlib ax.bar() function to plot the resulting dataframe. 您最好将数据与pandas聚合,然后再使用标准的matplotlib ax.bar()函数来绘制结果数据ax.bar()

If you insist on using seaborn, the following is somewhat of a "hackish" way of obtaining the desired result. 如果您坚持使用seaborn,则以下内容是获得所需结果的一种“骇人听闻”的方式。

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. 为了将每个小节稍微向左或向右移动,我创建了一个用于分类色调的虚拟分类列,并使用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM