Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add padding to a plot in python?

I am trying to add padding to the left and the right side of my plot. But when I change xlim and ylim; the image becomes smaller.

what am I doing wrong?

import matplotlib.pyplot as plt
plt.rcParams['text.usetex'] = False
from matplotlib.font_manager import FontProperties
import seaborn as sns
%matplotlib inline



df1=df['Total Acc'].round(4)*100 
labels = ['AWA','Rem', 'S1', 'S2', 'SWS', 'SX', 'ALL'] 


rows = [df1.loc[label] for label in labels] 
for row in rows:  
    row.plot(figsize=(10, 5), marker='o')


# http://matplotlib.org/api/legend_api.html ---set_bbox_to_anchor(bbox, transform=None)
myLegend=plt.legend(labels, bbox_to_anchor=(0., 1.15, 1., .102), prop ={'size':10}, loc=10, ncol=7,  #left, bottom, width, height
                title=r'LEARNING CURVE - Fp1_RF(20)')                                         
myLegend.get_title().set_fontsize('18') 


plt.ylim(97.5, 98.5)
plt.xlim(0, 45) 

plt.xlabel('# of samples per subject')
plt.ylabel('Accuracy')  

enter image description here

like image 762
Aizzaac Avatar asked Feb 16 '17 18:02

Aizzaac


People also ask

What is padding in Matplotlib?

Padding (height/width) between edges of adjacent subplots, as a fraction of the font size. Defaults to pad. rect : tuple (left, bottom, right, top), optional. A rectangle (left, bottom, right, top) in the normalized figure coordinate that the whole subplots area (including labels) will fit into. Default is (0, 0, 1, 1) ...

How do you add padding between subplots?

We can use the plt. subplots_adjust() method to change the space between Matplotlib subplots. The parameters wspace and hspace specify the space reserved between Matplotlib subplots. They are the fractions of axis width and height, respectively.


1 Answers

If your matplotlib figure is getting trimmed, you can use Tight Layout. Details provided here

In your code, try adding

plt.tight_layout()

Another option that you can try is to use subplots_adjust(). Basically it provides you control over the default spacing on the left, right, bottom, and top as well as the horizontal and vertical spacing between multiple rows and columns. Sample Example here

plt.subplots_adjust(left=0.5, right=0.5)
like image 61
Spandan Brahmbhatt Avatar answered Sep 22 '22 23:09

Spandan Brahmbhatt