Values are plotted out of order with a datetime axis

Viewed 119

This is the code for showing the 'Close' prices for Amazon, and visualizing the data using matplotlib.pyplot in Python.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('amzn_close.csv')
df = df.set_index(pd.DatetimeIndex(df['Date'].values))

plt.figure(figsize=(16,8))
plt.plot(df['Close'], label='Close')
plt.title('Close Price')
plt.xlabel('Date')
plt.ylabel('Price USD')
plt.show()

Unfortunately, it came out like this, with squiggly lines:

enter image description here

Can someone help me to present and visualize the data correctly?

amzn_close.csv

Date,Close
2021-03-05,3000.46
2021-04-01,3161.0
2021-03-17,3135.73
2021-02-23,3194.5
2021-03-10,3057.64
2021-03-16,3091.86
2021-03-18,3027.99
2021-02-25,3057.16
2021-04-15,3379.09
2021-03-22,3110.87
2021-04-14,3333.0
2021-03-25,3046.26
2021-03-24,3087.07
2021-02-26,3092.93
2021-04-20,3334.69
2021-04-19,3372.01
2021-04-16,3399.44
2021-04-08,3299.3
2021-03-08,2951.95
2021-03-30,3055.29
2021-03-02,3094.53
2021-03-09,3062.85
2021-02-24,3159.53
2021-02-22,3180.74
2021-04-22,3309.04
2021-03-01,3146.14
2021-03-15,3081.68
2021-03-26,3052.03
2021-04-05,3226.73
2021-03-31,3094.08
2021-03-03,3005.0
2021-04-23,3340.88
2021-04-26,3409.0
2021-03-19,3074.96
2021-03-23,3137.5
2021-04-21,3362.02
2021-03-29,3075.73
2021-04-12,3379.39
2021-04-07,3279.39
2021-04-13,3400.0
2021-04-27,3417.43
2021-04-06,3223.82
2021-03-12,3089.49
2021-03-11,3113.59
2021-03-04,2977.57
2021-04-09,3372.2
1 Answers
  • Two things to always verify are:
    1. The 'Date' should be set as a datetime64[ns] or DatetimeIndex dtype.
      • pd.to_datetime()
      • pd.DatetimeIndex()
      • Parse dates when importing data
    2. The value column, 'Close', should be a numeric dtype
    • Check the dtypes with df.info()

Use matplotlib directly

  • In this case, only the index needs to be sorted, because the y-axis is already numeric and the x-axis is already a datetime dtype.
  • The csv can also be read in with:
    • df = pd.read_csv('amzn_close.csv', parse_dates=['Date'], index_col=['Date'])
# load and format the data
df = pd.read_csv('amzn_close.csv')
df = df.set_index(pd.DatetimeIndex(df['Date'].values))

# sort the index
df.sort_index(inplace=True)

# plot
plt.figure(figsize=(16, 7))
plt.plot(df['Close'], label='Close')
plt.title('Close Price')
plt.xlabel('Date')
plt.ylabel('Price USD')
plt.show()

Use pandas.DataFrame.plot

  • Doesn't require sorting the index
# load the data
df = pd.read_csv('amzn_close.csv', parse_dates=['Date'], index_col=['Date'])

# plot the data
df.plot(figsize=(16, 7), title='Close Price', ylabel='Price USD', rot=0, legend=False)

Use seaborn.lineplot

  • Doesn't require sorting the index
# load the data
df = pd.read_csv('amzn_close.csv', parse_dates=['Date'], index_col=['Date'])

# plot
fig, ax = plt.subplots(figsize=(16, 7))
sns.lineplot(data=df, ax=ax, legend=False)
ax.set(title='Close Price', xlabel='Date', ylabel='Price USD')

Output for all implementations

enter image description here

Notes

  • Package versions:
    • pandas v1.2.4
    • seaborn v0.11.1
    • matplotlib v3.3.4
Related