I want to add plots to subplots using
fig, axarr = plt.subplots(2, 2)
plt.sca(axarr[0, 0])
result = desire_salary.pivot_table('city', 'cult', aggfunc='count')
axarr[0, 0] = result.plot(kind='bar', alpha=0.75, rot=0, label="Presence / Absence of cultural centre")
axarr[0, 0].set_xlabel("Cultural centre")
axarr[0, 0].set_ylabel("Frequency")
axarr[0, 0].set_title('Salary and culture')
axarr[0, 0].plot(result[[0]], color='red')
plt.sca(axarr[0, 1])
axarr[0, 1] = df.plot()
plt.sca(axarr[1, 0])
plt.show()
But one added to subplot, but others no. I get this graphs What I do wrong?
asked Jun 20, 2016 at 19:55
1 Answer 1
When you use pandas (I assume), the surest way to ensure which axes is used is to pass the reference to the axes to the plotting function using the ax=
parameter
fig, axarr = plt.subplots(2, 2)
result = desire_salary.pivot_table('city', 'cult', aggfunc='count')
result.plot(kind='bar', alpha=0.75, rot=0, label="Presence / Absence of cultural centre", ax=axarr[0, 0])
axarr[0, 0].set_xlabel("Cultural centre")
axarr[0, 0].set_ylabel("Frequency")
axarr[0, 0].set_title('Salary and culture')
axarr[0, 0].plot(result[[0]], color='red')
df.plot(ax=axarr[0, 1])
plt.show()
answered Jun 20, 2016 at 20:18
3 Comments
NineWasps
Why if I chenge
fig, axarr = plt.subplots(2, 2)
to fig, axarr = plt.subplots(2, 1)
, it returns ` plt.sca(axarr[0, 1]) IndexError: too many indices for array`?Diziet Asahi
if you do
fig, axarr = plt.subplots(2, 1)
you only have 2 subplots on 2 rows, 1 column. In that case subplots
returns a 1 dimension array, so the valid indices are axarr[0]
and axarr[1]
NineWasps
but if I want 3 plots? 2 at the top and 1 at the bottom?
lang-py
axarr[0, 1] = df.plot()
withdf.plot(ax=axarr[0, 1])
?