1

I am using a combination of pandas and matplotlib to plot three values for several categories. I would like one plot to have its own axis, and the other two to share an axis.

Close, but illustrates the issue with why I need dual axes:

pd.DataFrame([[1,2,3], [500,600,700], [500, 700, 650]], columns=['foo', 'bar','baz'],
             index=['a','b','c']).T.plot(kind='bar')

the problem

Instead, I would like a second axis for the a bars. My attempt:

smol = pd.DataFrame([[1,2,3], [500,600,700], [500, 700, 650]], columns=['foo', 'bar','baz'],
        index=['a','b','c']).T

fig = plt.figure(figsize=(10,5)) # Create matplotlib figure

ax = fig.add_subplot(111) # Create matplotlib axes
ax2 = ax.twinx() # Create another axes that shares the same x-axis as ax.

smol['a'].plot(kind='bar', color='red', ax=ax, width=0.3, 
                    position=1, edgecolor='black')
smol['b'].plot(kind='bar', color='blue', ax=ax2, width=0.3, 
                 position=0, edgecolor='black')

ax.set_ylabel('Small scale')
ax2.set_ylabel('Big scale')

plt.show()

the attempt

Unfortunately, adding

smol['c'].plot(kind='bar', color='green', ax=ax2, width=0.3, 
                 position=0, edgecolor='black') 

produces:

yikes

How can I have b and c share an axis, but appear next to each other, as in the first attempt?

1 Answer 1

2

I've used secondary_y keyword. The code is also considerably shorter

smol = pd.DataFrame([[1,2,3], [500,600,700], [500, 700, 650]], columns=['foo', 'bar','baz'],
        index=['a','b','c']).T

ax = smol.plot(kind="bar", secondary_y=['b', 'c'])

ax.set_ylabel('Small scale')
ax.right_ax.set_ylabel('Big scale')

plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.