1

I have this code:

import pandas as pd
from pandas import datetime
from pandas import DataFrame as df
import matplotlib
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import datetime
start = datetime.date(2016,1,1)
end = datetime.date.today()
stock = 'fb'
fig = plt.figure(dpi=1400)
data = web.DataReader(stock, 'yahoo', start, end)
fig, ax = plt.subplots(dpi=720)
data['vol_pct'] = data['Volume'].pct_change()
data.plot(y='vol_pct', ax = plt.gca(), title = 'this is the title \n second line')

ax.set(xlabel="Date")
ax.legend(loc='upper center', bbox_to_anchor=(0.32, -0.22), shadow=True, ncol=2)
plt.savefig('Test')

This is an example of another code but the problem is the same: enter image description here

At bottom of the plot you can see that the legend is being cut out. In another plot of a different code which i am working on, even the ylabel is also cut when i save the plot using plt.savefig('Test').How can i can fix this?

Slartibartfast
  • 1,058
  • 4
  • 26
  • 60

2 Answers2

8

It's a long-standing issue with .savefig() that it doesn't check legend and axis locations before setting bounds. As a rule, I solve this with the bbox_inches argument:

plt.savefig('Test', bbox_inches='tight')

This is similar to calling plt.tight_layout(), but takes all of the relevant artists into account, whereas tight_layout will often pull some objects into frame while cutting off new ones.

I have to tell pyplot to keep it tight more than half the time, so I'm not sure why this isn't the default behavior.

Elliott Collins
  • 660
  • 5
  • 8
1

plt.subplots_adjust(bottom=0.4 ......)

I think this modification will satisfy you.

Or maybe you can relocate the legend to loc="upper left"

https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots_adjust.html

please also checked this issue which raised 8 years ago..

Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Erol Erdogan
  • 128
  • 9