Skip to content
Advertisement

Changing margin on mplfinance plot when savefig

I have the following code which produces finance plot:

from pandas_datareader import data as web
import pandas as pd
import mplfinance as mpf
df = web.DataReader('goog','yahoo', start="2021-07-3", end="2021-09-12")
mpf.plot(df, style='charles', type = 'candle', volume=True, figratio=(12,8), title='large title', savefig = 'testimage.jpg')

enter image description here

But the image which it generated left a lot of space on all side, so i include the parameter tight_layout=True however now i a getting an image which looks like this:

enter image description here

The title is inside the image. Could you advise how can i change the margin where the left and right are tight and title is on top. Also how can you add a secondary title to the image

Advertisement

Answer

Extra configuration can be passed to position the title when title option is passed as a dictionary.

For example,

config = dict(
    style="charles",
    type="candle",
    volume=True, 
    figratio=(12,8),
    title={"title": "large title", "y": 1},
    tight_layout=True
)
fig = mpf.plot(df, **config)

To add a secondary title. You’ll need control of the plot axis.

You can write:

ax1 = plt.axes([0,0,1,0.4])
ax1.set_title("Volume")
ax1.yaxis.set_label_position("right")
ax1.yaxis.tick_right()

ax2 = plt.axes([0,0.6,1,0.4])
ax2.set_title("Price")
ax2.yaxis.set_label_position("right")
ax1.yaxis.tick_right()


config = dict(
    style="charles",
    type="candle",
    volume=ax1,
    ax=ax2,
    figratio=(12,8),
    num_panels=2,
    tight_layout=True
)

fig = mpf.plot(df, **config)

controlled axis for matplotlib finance

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement