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
Two things are happening here:
bbox_inches='tight' crops the resulting image downThe 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With