Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)

Thanks for your help

Larry

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
165 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...