TransWikia.com

set year to the x labels in matplotlib

Stack Overflow Asked by NArgento on February 12, 2021

I have a dataframe as follows

    Out[125]: 
         Google Tends: unem. insurance  Unemp. Rate
YM                                                 
2004-01                           0.34     0.270968
2004-02                           0.33     0.270968
2004-03                           0.00     0.270968
2004-04                           0.17     0.270968
2004-05                           0.15     0.270968

and I want to plot and I want the year number is written below the x-axis as label of the data. This is the code that I found

years = mdates.YearLocator()  
years_fmt = mdates.DateFormatter('%Y')


fig, ax = plt.subplots()

ax.plot(end.index, end['Google Tends: unem. insurance'])

ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)
ax.format_xdata = mdates.DateFormatter('%Y')

plt.show()

I don’t get error messages but neither the labels

enter image description here

One Answer

  • YM must first be converted to a datetime format. Currently, the date is just a str type.
    • YM should be converted to a datetime prior to any .groupby.
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

data = {'YM': ['2004-01', '2004-02', '2004-03', '2004-04', '2004-05', '2005-01', '2006-01'],
        'Google Tends: unem. insurance': [0.34, 0.33, 0.0, 0.17, 0.15, 0.12, 0.34],
        'Unemp. Rate': [0.270968, 0.270968, 0.270968, 0.270968, 0.270968, 0.270968, 0.270968]}

df = pd.DataFrame(data)

        YM  Google Tends: unem. insurance  Unemp. Rate
0  2004-01                           0.34     0.270968
1  2004-02                           0.33     0.270968
2  2004-03                           0.00     0.270968
3  2004-04                           0.17     0.270968
4  2004-05                           0.15     0.270968
5  2005-01                           0.12     0.270968
6  2006-01                           0.34     0.270968

# convert YM to datetime
df.YM = pd.to_datetime(df.YM, format='%Y-%m')

# plot
years = mdates.YearLocator()  
years_fmt = mdates.DateFormatter('%Y')

fig, ax = plt.subplots()
ax.plot('YM', 'Google Tends: unem. insurance', data=df)

ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)

enter image description here

Answered by Trenton McKinney on February 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP