matplotlib.axis.axes error in mplfinance for volume

2.5k Views Asked by At

I am working with stock data which looks like daily.head

enter image description here

My code is:

import pandas as pd
import mplfinance as mpf
import matplotlib.pyplot as plt
data = pd.read_csv('/content/drive/MyDrive/python/TEchAnalysis.csv')

figdims=(15,10)
fig , ax = plt.subplots(figsize=figdims)
mpf.plot(daily , type='candle' , mav=(5,10,20,50,100) ,volume=True , ax=ax )

I am having the error

ValueError: `volume` must be of type `matplotlib.axis.Axes`

Please can somebody explain me this error & how to fix it?

2

There are 2 best solutions below

2
On

If you specify external axes, you should also specify axes to display the volume. According to the documentation about external axes:

Please note the following:

  • Use kwarg ax= to pass any matplotlib Axes that you want into mpf.plot()
  • If you also want to plot volume, then you must pass in an Axes instance for the volume, so instead of volume=True, use volume=<myVolumeAxesInstance><myVolumeAxesInstance>.
  • If you specify ax= for mpf.plot() then you must also specify ax= for all calls to make_addplot().
0
On

Try this:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import mplfinance as mpf
import pandas as pd
import yfinance as yf
%matplotlib inline

df = yf.download('aapl', '2015-01-01', '2021-01-01')
df.rename(columns= {'Adj Close': 'Adj_close'}, inplace= True)
df1 = df.copy().loc['2015-01':'2015-02', :]

fig, ax1 = plt.subplots(figsize= (12, 6))
fig.set_facecolor('#ffe8a8')
ax1.set_zorder(1)
ax1.grid(True, color= 'k', linestyle= '--')
ax1.set_frame_on(False)
ax2 = ax1.twinx()
ax2.grid(False)
mpf.plot(df1, ax= ax1, type= 'candle', volume= ax2, xlim= (df1.index[0], 
df1.index[-1]))
plt.show()

It works fairly well, giving some options to customize. This is the output: enter image description here