Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib: if I set fig height, x legend is cut off

I'm trying to set the figure size with fig1.set_size_inches(5.5,3) on python, but the plot produces a fig where the x label is not completely visibile. The figure itself has the size I need, but it seems like the axis inside is too tall, and the x label 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 file:

image with 5.5x3 inch

like image 415
otmezger Avatar asked Dec 20 '22 08:12

otmezger


2 Answers

You could order the save method to take the artist of the x-label into consideration.

This is done with the bbox_extra_artists and the tight layout. The resulting code would be:

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')
like image 155
Korem Avatar answered Jan 09 '23 17:01

Korem


It works for me if I initialize the figure with the 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

like image 20
askewchan Avatar answered Jan 09 '23 19:01

askewchan