Skip to content Skip to sidebar Skip to footer

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). The probem I have is that the graphs are overlapped and

Solution 1:

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

Post a Comment for "Twinx And Sns.barplot Seaborn Are Overlapping Bars"