Matplotlib: if I set the height of the drawing, x the legend is cropped

I am trying to set the size of a figure using fig1.set_size_inches(5.5,3) in python, but the graph creates a drawing where the x mark is not completely visible. The shape itself has the size that I need, but it seems that the axis inside is too tall, and the x mark just doesn't fit anymore.

here is my code:

 fig1 = plt.figure() fig1.set_size_inches(5.5,4) fig1.set_dpi(300) ax = fig1.add_subplot(111) ax.grid(True,which='both') ax.hist(driveDistance,100) ax.set_xlabel('Driven Distance in km') ax.set_ylabel('Frequency') fig1.savefig('figure1_distance.png') 

and here is the result of the file:

image with 5.5x3 inch

+4
source share
2 answers

You can order a save method to take into account the x-tag artist.

This is done using bbox_extra_artists and a tight layout. Final code:

 import matplotlib.pyplot as plt fig1 = plt.figure() fig1.set_size_inches(5.5,4) fig1.set_dpi(300) ax = fig1.add_subplot(111) ax.grid(True,which='both') ax.hist(driveDistance,100) xlabel = ax.set_xlabel('Driven Distance in km') ax.set_ylabel('Frequency') fig1.savefig('figure1_distance.png', bbox_extra_artists=[xlabel], bbox_inches='tight') 
+8
source

This works for me if I initialize the figure with figsize and dpi as kwargs :

 from numpy import random from matplotlib import pyplot as plt driveDistance = random.exponential(size=100) fig1 = plt.figure(figsize=(5.5,4),dpi=300) ax = fig1.add_subplot(111) ax.grid(True,which='both') ax.hist(driveDistance,100) ax.set_xlabel('Driven Distance in km') ax.set_ylabel('Frequency') fig1.savefig('figure1_distance.png') 

driveDistance

+2
source

All Articles