0

My code currently looks like:

fig = plt.figure(figsize=(10, 5))

ax = plt.gca()

plt.plot(new_stripped_df["Month"],new_stripped_df['(ii) Monthly difference, Natural log of the Exchange Rate per U.S. Dollar'])

plt.title('Monthly Growth in Nominal Exchange rates',fontdict={'fontname':'Calibri','fontsize':15})

plt.xlabel("Date",fontdict={'fontname':'Calibri','fontsize':10})

plt.ylabel("Log Change",fontdict={'fontname':'Calibri','fontsize':10})

plt.tight_layout()

plt.show()

Which returns:

Graph

As you can see the x axis tickers are unreadable and I want to include only every 5 years from 1960 to 1990 on the x axis. new_stripped_df["Month"] is in format: Jan 1960 all the way up to Dec 1990.

not_speshal
  • 22,093
  • 2
  • 15
  • 30
zhihao000
  • 1
  • 1
  • 1
    It looks like you are using pandas dataframe. In this case, it would be easier to use the pandas plotting methods, because they automatically fit the x/y ticks. Please also have a look at this question, whether it answers your question: https://stackoverflow.com/questions/25279475/matplotlib-pyplot-tick-control-and-showing-date – MarcelCode Mar 08 '22 at 15:49
  • 2
    Note that `new_stripped_df["Month"]` should be in the pandas datetime format. – JohanC Mar 08 '22 at 16:02

1 Answers1

1

Make sure the x-axis data is datetime. Then, you need to use YearLocator().

import pandas as pd
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from matplotlib.dates import YearLocator, DateFormatter

# Data
df = pd.DataFrame({"val": list(range(1200))})
df["dates"] = [datetime.today() - timedelta(days=x) for x in range(0, 24000, 20)]

# Plot
f, ax = plt.subplots(figsize = [12, 7])
ax.plot(df["dates"], df["val"])
ax.xaxis.set_major_locator(YearLocator(5))
ax.xaxis.set_major_formatter(DateFormatter("%Y"))
d.b
  • 32,245
  • 6
  • 36
  • 77