Search code examples
pythondatematplotlibsubplotx-axis

Dates on -Axis showing as Jan 51 instead of Jan 20


First question here so if something isnt clear, I can clarify...

if I comment out the last three lines my chart looks ok - but the dates on X axis dont show up in the format I want (MMM-YY) and if I change to the below per other things I've read I get Jan 51 instead of Jan 20?

hoping for some ideas!

thanks,

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

data= [['2020-01-01',70,'bra'],['2020-01-01',80,'mex'],
       ['2020-01-05',40,'bra'],['2020-01-05',50,'mex'],
       ['2020-01-09',30,'bra'],['2020-01-09',20,'mex']]
df=pd.DataFrame(data,columns=['date','value','country'])
df['date']=pd.to_datetime(df['date'],format = '%Y-%m-%d')


#create subplot 
fig = plt.figure(figsize=(12,5))
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)

for key,grp in df.groupby(['country']):
    ax1 = grp.plot(kind='line',x='date', y='value', ax=ax1,label=key
                   ,title='Values')
    ax1.set_axisbelow(True)
    ax1.grid(linestyle='-',linewidth='0.5',color='black')
    ax1.set_ylim([0,100])
    ax1.set_ylabel('values')
    monthyearFmt = mdates.DateFormatter('%b %y')
    ax1.xaxis.set_major_formatter(monthyearFmt) 
    ax1.xaxis.set_major_locator(mdates.DayLocator(interval=60))

Solution

  • Use x_compat=True:

    #create subplot 
    fig = plt.figure(figsize=(12,5))
    ax1 = fig.add_subplot(1,2,1)
    ax2 = fig.add_subplot(1,2,2)
    
    for key,grp in df.groupby(['country']):
        ax1 = grp.plot(kind='line',x='date', y='value', ax=ax1,label=key
                       ,title='Values', x_compat=True)
        ax1.set_axisbelow(True)
        ax1.grid(linestyle='-',linewidth='0.5',color='black')
        ax1.set_ylim([0,100])
        ax1.set_ylabel('values')
        monthyearFmt = mdates.DateFormatter('%b %d %Y')
        ax1.xaxis.set_major_formatter(monthyearFmt) 
        ax1.xaxis.set_major_locator(mdates.DayLocator(interval=2))
    

    Output:

    enter image description here