Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib + python: figure size for fig.figimage and fig.savefig

I'm trying to add a png image to a plot created with matplotlib in python.

Here is my plot code

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt


fig = plt.figure(figsize=(5.5,3),dpi=300)
ax = fig.add_subplot(111)
ax.grid(True,which='both')

ax.plot([0,1,2,3],[5,2,6,3],'o')

xlabel = ax.set_xlabel('xlab')
ax.set_ylabel('ylab')


from PIL import Image
import numpy as np

im = Image.open('./lib/Green&Energy-final-roundonly_xsmall.png')
im_w = im.size[0]
im_h = im.size[1]
# We need a float array between 0-1, rather than
# a uint8 array between 0-255
im = np.array(im).astype(np.float) / 255

fig.figimage(im,fig.bbox.xmax - im_w - 2,2,zorder=10 )
fig.savefig('test.png',bbox_extra_artists=[xlabel], bbox_inches='tight')

the figure has 513x306 px saved as pdf, but the value of fig.bbox.xmax is 1650.0... This is why my figure does not appear.... how can I know the size of the image before it's printed, so I can know where to put my im?

thanks

like image 328
otmezger Avatar asked Apr 14 '26 15:04

otmezger


1 Answers

Two things are happening here:

  1. As @tcaswell mentioned, bbox_inches='tight' crops the resulting image down
  2. You're not actually saving the image at 300 dpi, you're saving it at 100 dpi

The second item is a common gotcha. By default, matplotlib saves figures at a different dpi (configurable in the rc params) that the figure's native dpi.

To get around this, pass in the fig.dpi to fig.savefig:

fig.savefig(filename, dpi=fig.dpi, ...)

To get around cropping things down, either a) leave bbox_inches='tight' out entirely, or b) resize things inside of the figure instead. A quick way to accomplish (b) is to use fig.tight_layout, though it won't be "tightly" cropped the way that using bbox_inches with savefig will.

like image 77
Joe Kington Avatar answered Apr 17 '26 04:04

Joe Kington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!