Search code examples
pythonmatplotlibaxis-labels

x axis label disappearing in matplotlib and basic plotting in python


I am new to matplotlib, and I am finding it very confusing. I have spent quite a lot of time on the matplotlib tutorial website, but I still cannot really understand how to build a figure from scratch. To me, this means doing everything manually... not using the plt.plot() function, but always setting figure, axis handles.

Can anyone explain how to set up a figure from the ground up?

Right now, I have this code to generate a double y-axis plot. But my xlabels are disappearing and I dont' know why

fig, ax1 = plt.subplots()
ax1.plot(yearsTotal,timeseries_data1,'r-')
ax1.set_ylabel('Windspeed [m/s]')
ax1.tick_params('y',colors='r')

ax2 = ax1.twinx()
ax2.plot(yearsTotal,timeseries_data2,'b-')
ax2.set_xticks(np.arange(min(yearsTotal),max(yearsTotal)+1))
ax2.set_xticklabels(ax1.xaxis.get_majorticklabels(), rotation=90)
ax2.set_ylabel('Open water duration [days]')
ax2.tick_params('y',colors='b')

plt.title('My title')
fig.tight_layout()
plt.savefig('plots/my_figure.png',bbox_inches='tight')
plt.show()

Solution

  • Because you are using a twinx, it makes sense to operate only on the original axes (ax1). Further, the ticklabels are not defined at the point where you call ax1.xaxis.get_majorticklabels().

    If you want to set the ticks and ticklabels manually, you can use your own data to do so (although I wouldn't know why you'd prefer this over using the automatic labeling) by specifying a list or array

    ticks = np.arange(min(yearsTotal),max(yearsTotal)+1)
    ax1.set_xticks(ticks)
    ax1.set_xticklabels(ticks)
    

    Since the ticklabels are the same as the tickpositions here, you may also just do

    ax1.set_xticks(np.arange(min(yearsTotal),max(yearsTotal)+1))
    plt.setp(ax1.get_xticklabels(), rotation=70)
    

    Complete example:

    import matplotlib.pyplot as plt
    import numpy as np; np.random.seed(1)
    
    yearsTotal = np.arange(1977, 1999)
    timeseries_data1 = np.cumsum(np.random.normal(size=len(yearsTotal)))+5
    timeseries_data2 = np.cumsum(np.random.normal(size=len(yearsTotal)))+20
    
    fig, ax1 = plt.subplots()
    ax1.plot(yearsTotal,timeseries_data1,'r-')
    ax1.set_ylabel('Windspeed [m/s]')
    ax1.tick_params('y',colors='r')
    ax1.set_xticks(np.arange(min(yearsTotal),max(yearsTotal)+1))
    plt.setp(ax1.get_xticklabels(), rotation=70)
    
    ax2 = ax1.twinx()
    ax2.plot(yearsTotal,timeseries_data2,'b-')
    ax2.set_ylabel('Open water duration [days]')
    ax2.tick_params('y',colors='b')
    
    plt.title('My title')
    fig.tight_layout()
    plt.show()
    

    enter image description here