econ99
econ99

Reputation: 3

Matplotlib missing x tick labels

Once I run the code below, the x tick labels for the third plot, ax3, does not show up. Yet, I only removed the x tick labels for ax1 and ax2. Any solution to having the dates appear on the x axis of my third plot, ax3?

plt.figure()
ax1 = plt.subplot2grid((8,1),(0,0), rowspan=4, colspan=1)
ax1.yaxis.set_major_locator(mticker.MaxNLocator(nbins=10, prune='lower'))
plt.setp(ax1.get_xticklabels(), visible=False)

ax2 = plt.subplot2grid((8,1),(4,0), rowspan=2, colspan=1, sharex = ax1)
plt.setp(ax2.get_xticklabels(), visible=False)

ax3 = plt.subplot2grid((8,1),(6,0), rowspan=2, colspan=1, sharex = ax1)
ax3.xaxis.set_major_locator(mticker.MaxNLocator(10))
ax3.xaxis.set_minor_locator(mticker.MaxNLocator(20))

'''
# This has been ***removed*** in corrected version
for label in ax3.xaxis.get_ticklabels():
        label.set_rotation(45)
        plt.xlabel('Dates') #This label does not appear in the figure either
'''

ax3.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper'))

main.dropna(inplace=True)                          
main['sales1'].plot(ax=ax1)
main['sales2'].plot(ax=ax1)
cmain.plot(ax=ax2)
main[['rollsales1', 'rollsales2']].plot(ax=ax3)

'''
# This has been added to corrected version.   
plt.setp(ax3.xaxis.get_label(), visible=True, text='Dates')
plt.setp(ax3.get_xticklabels(), visible=True, rotation=30, ha='right')
'''    

plt.show()

Upvotes: 0

Views: 12484

Answers (1)

James
James

Reputation: 36756

In matplotlib, using sharex or sharey turns off the ticklabels by default in version 2. So you can drop the pieces of code that set the label visibility to False. Also, rather than iterating over each label to change the parameters, you can set the parameters for all of them in one shot using setp.

I had to make fake data to simulate your graphs, so my data may look bizarre.

plt.figure()
ax1 = plt.subplot2grid((8,1),(0,0), rowspan=4, colspan=1)
ax2 = plt.subplot2grid((8,1),(4,0), rowspan=2, colspan=1, sharex=ax1)
ax3 = plt.subplot2grid((8,1),(6,0), rowspan=2, colspan=1, sharex=ax1)

ax1.yaxis.set_major_locator(mticker.MaxNLocator(nbins=10, prune='lower')
ax3.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper'))

main.dropna(inplace=True)
main['sales1'].plot(ax=ax1)
main['sales2'].plot(ax=ax1)
cmain.plot(ax=ax2)
main[['rollsales1', 'rollsales2']].plot(ax=ax3)

# set the xaxis label
plt.setp(ax3.xaxis.get_label(), visible=True, text='Dates')
# set the ticks
plt.setp(ax3.get_xticklabels(), visible=True, rotation=30, ha='right')
# turn off minor ticks
plt.minorticks_off()
plt.show()

enter image description here

Upvotes: 2

Related Questions