Matplotlib set year on x axis

1k views Asked by At

i would like to have a plot of nasdaq market index that has on x axis the years since 1971 and on y axis the values.

dataframe = pd.read_csv('nasdaq-historical-chart.csv', usecols=[1], engine='python')
dataset = dataframe.values

df = pd.read_csv('nasdaq-historical-chart.csv',parse_dates=True)
df['date'] = pd.to_datetime(df['date'])
df['year'] = df['date'].dt.year
plt.plot(dataset)
plt.figure(figsize=(25,10))
plt.plot(df['year'], dataset)
plt.title('NASDAQ historical chart',fontsize=24)
plt.xlabel('Time',fontsize=14)
plt.ylabel('Value',fontsize=14)
plt.tick_params(axis='both',labelsize=14)
plt.show()

In this way i have the right plot but without years on x axis enter image description here

If i put:

plt.plot(df['year'], dataset)

i have: enter image description here

why the plot changed? How can i modify it?

1

There are 1 answers

1
Joe On

I created some data similar to yours as example, and you can do in a similar way:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'date':['1971-1-1','1971-1-2','1971-1-3','1971-1-4','1971-1-5','1971-1-6','1971-1-7','1971-1-8','1971-1-9',
                       '1971-1-10', '1971-1-11', '1971-1-12', '1972-1-1','1972-1-2','1972-1-3','1972-1-4',
                       '1972-1-5','1972-1-6','1972-1-7','1972-1-8','1972-1-9','1972-1-10', '1972-1-11', '1972-1-12'],
                   'values':[150, 130, 100, 95, 100, 105, 200, 180, 170, 160, 150, 155, 155, 170, 190, 192, 195, 200, 220,
                        230, 220, 210, 230, 235]})
print (df)
df['date'] = pd.to_datetime(df['date'], format='%Y-%d-%m')
plt.figure(figsize=(25,10))
plt.plot(df['date'], df['values'])
plt.title('NASDAQ historical chart',fontsize=24)
plt.xlabel('Time',fontsize=14)
plt.ylabel('Value',fontsize=14)
plt.tick_params(axis='both',labelsize=14)
plt.show()

enter image description here