10

I had met an error code by following the video tutorial of sentdex. When i want to plot a bar graph on ax2 for my Volume, however, it give me error code as listed at the topic. Please help. I am new in Python 0 experience in programming.

import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
style.use('ggplot')

df = pd.read_csv('C:\\Users\\ngjun95\\Downloads\\7120.KL.csv',     parse_dates=True, index_col=0)
df['100ma'] = df['Adj Close'].rolling(window=100, min_periods=0).mean()

print(df.head())

ax1 = plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1)
ax2 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1, sharex=ax1)

ax1.plot(df.index, df['Adj Close'])
ax1.plot(df.index, df['100ma'])
ax2.bar(df.index, df['Volume'])

plt.show()
Ng Jun
  • 111
  • 1
  • 1
  • 6

2 Answers2

11

Seems like a date conversion issue between Matplotlib and Numpy. https://github.com/matplotlib/matplotlib/issues/9610

I had the same issue for the longest time.

df.index.to_pydatetime() works for me.

Saeed
  • 1,848
  • 1
  • 18
  • 26
  • Here is more info on my story with this issue: in older versions of Pandas (probably around .17 or .18; not exactly sure), I had no such issues. Then once I started working with .2, I faced this issue with automatic dates on x axis when plotting correctly-indexed time series. Since then, the `.to_pydatetime()` solution worked for me. But it had some shortcomings, such as empty spaces on graphs where there was no data available for some dates. Fortunately, a few days ago, I updated to Pandas 0.21.1 and no longer need this work around. So, I suggest you update and see what happens. – Saeed Dec 18 '17 at 18:12
3

Old topic, but df.index.to_pydatetime() didn't solve my issue with seaborn.regplot(). For me, date2num worked perfectly.

import matplotlib.dates as mdates

sns.regplot(x=mdates.date2num(df.index), y=df['target'])
Mehdi
  • 999
  • 13
  • 11