Home > Software design >  Plot multiple mplfinance plots sharing x axis
Plot multiple mplfinance plots sharing x axis

Time:10-31

I am trying to plot 5 charts one under the other with mplfinance.

This works:

for coin in coins:
    mpf.plot(df_coins[coin], title=coin, type='line', volume=True, show_nontrading=True)

However each plot is a separate image in my Python Notebook cell output. And the x-axis labelling is repeated for each image.

I try to make a single figure containing multiple subplot/axis, and plot one chart into each axis:

from matplotlib import pyplot as plt

N = len(df_coins)
fig, axes = plt.subplots(N, figsize=(20, 5*N), sharex=True)

for i, ((coin, df), ax) in zip(enumerate(df_coins.items()), axes):
    mpf.plot(df, ax=ax, title=coin, type='line', volume=True, show_nontrading=True)

This displays subfigures of the correct dimensions, however they are not getting populated with data. Axes are labelled from 0.0 to 1.0 and the title is not appearing.

What am I missing?

CodePudding user response:

There are two ways to subplot. One is to set up a figure with mplfinance objects. The other way is to use your adopted matplotlib subplot to place it.

yfinace data

import matplotlib.pyplot as plt
import mplfinance as mpf
import yfinance as yf

tickers = ['AAPL','GOOG','TSLA']
data = yf.download(tickers, start="2021-01-01", end="2021-03-01", group_by='ticker')

aapl = data[('AAPL',)]
goog = data[('GOOG',)]
tsla = data[('TSLA',)]

mplfinance

fig = mpf.figure(style='yahoo', figsize=(12,9))
#fig.subplots_adjust(hspace=0.3)
ax1 = fig.add_subplot(3,1,1, sharex=ax3)
ax2 = fig.add_subplot(3,1,2, sharex=ax3)
ax3 = fig.add_subplot(3,1,3)

mpf.plot(aapl, type='line', ax=ax1, axtitle='AAPL', xrotation=0)
mpf.plot(goog, type='line', ax=ax2, axtitle='GOOG', xrotation=0)
mpf.plot(tsla, type='line', ax=ax3, axtitle='TSLA', xrotation=0)
ax1.set_xticklabels([])
ax2.set_xticklabels([])

matplotlib

N = len(tickers)
fig, axes = plt.subplots(N, figsize=(20, 5*N), sharex=True)

for df,t,ax in zip([aapl,goog,tsla], tickers, axes):
    mpf.plot(df, ax=ax, axtitle=t, type='line', show_nontrading=True)# volume=True 

CodePudding user response:

In addition to the techniques mentioned by @r-beginners there is another technique that may work for you in the case where all plots share the same x-axis. That is to use mpf.make_addplot().

aps = []
for coin in coins[1:]:
    aps.append(mpf.make_addplot(df_coins[coin]['Close'], title=coin, type='line'))

coin = coins[0]
mpf.plot(df_coins[coin],axtitle=coin,type='line',volume=True,show_nontrading=True,addplot=aps)

If you choose to do type='candle' instead of 'line', then change

df_coins[coin]['Close']

to simply

df_coins[coin]
  • Related