Skip to content Skip to sidebar Skip to footer

Python Pandas Plotting Shift X-axis If Twinx Two Y-axes

I have a dataframe with 3 columns: one of them is a 'groupby' column, the other two are 'normal' columns with values. I want to generate a boxplot and a bar chart as well. On the b

Solution 1:

It's because the boxplot and the bar plot do not use the same xticks even if the labels are the same.

df.boxplot(column='B', by='A')
plt.xticks()

(array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10]), <a list of 10 Text xticklabel objects>)

df.groupby('A').count()['B'].plot(kind='bar')
plt.xticks()

(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), <a list of 10 Text xticklabel objects>)

At a glance it looks to me like an inconsistency which should be fixed in matplotlib boxplot(), but I might just be overlooking the rationale.

As a workaround use matplotlib bar(), that allows you to specify the xticks to match those of the boxplot (I did not found a way to do it with df.plot(kind='bar').

df.boxplot(column='B', by='A')
plt.twinx()
plt.bar(left=plt.xticks()[0], height=df.groupby('A').count()['B'],
        align='center', alpha=0.3)

enter image description here

Post a Comment for "Python Pandas Plotting Shift X-axis If Twinx Two Y-axes"