-1

I am trying to show the x values every couple of months instead of showing all of them. Currently it is showing every value. Which clutters the x axis. Is there an easy way to fix? The x value is formatted as a date.

thanks!

Here is my code:

import matplotlib.pyplot as plt
import pandas as pd

spread = pd.read_csv('I10Y3MTS_data.csv')
plt.title('10yr 3mo Yield Spread')
plt.plot(spread.Date, spread.Spread)
plt.show()

graph

Don
  • 3,876
  • 10
  • 47
  • 76

1 Answers1

0

The main reason for the issue is that, when you read the data from a csv file, the date field will be taken as a string. You can check this by using spread.info(). The problem should be resolved (to some extent) if you convert it to datetime format. Changing it will let matplotlib know that these are datetimes and it will try to automatically give the right frequency. Use to_datetime() to convert the string column to datetime. As I don't have the data you used, taking another dataset.

spread=pd.read_csv('austin_weather.csv')
spread.Date = pd.to_datetime(spread.Date, format="%d-%m-%Y") ## Format = your input datetime format that is being provided
plt.figure(figsize=(6, 3))
plt.plot(spread.Date, spread.TempHighF)

PLOT

enter image description here

If, however, you still want to change it (format, rotation, frequnecy, etc.), you can use the below code to adjust it further...

import matplotlib.dates as mdates
# set monthly locator
plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=3)) ##Show ticks once every 3 months
# set formatter
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b-%Y')) ##Format to MMM - YEAR
# set font and rotation for date tick labels
plt.gcf().autofmt_xdate()

Updated plot

enter image description here

Redox
  • 9,321
  • 5
  • 9
  • 26