1

How can i remove those white borders? Why axes are starting from -100,-100? And, finally, how can i set size for final png image?

import matplotlib.pyplot as plt
import matplotlib
import numpy as np

im = plt.imread('pitch.png')
implot = plt.imshow(im, aspect='auto')

dpi=96

if dpi is None:
        dpi = matplotlib.rcParams['savefig.dpi']
dpi = float(dpi)

fig = plt.figure(figsize=(620/dpi, 579/dpi), dpi=dpi)
ax = fig.add_axes([0, 0, 1, 1], frame_on=False)
ax.imshow(im, interpolation='none')

x, y = np.genfromtxt('coords.csv', delimiter=',', unpack=True)
plt.plot(x,y, "o")

plt.savefig('dybala.png', bbox_inches='tight')

enter image description here

slash89mf
  • 1,057
  • 2
  • 13
  • 35

1 Answers1

0

The white borders are caused by using imshow and plot in the same plot. When using imshow alone the limits of the axis will be set to the limit of the image. However, when plotting the axes are updated automatically.

The simplest solution to this is to get the axes limits after imshow and re-apply them to the figure after plotting. For example, first get the limits:

implot = plt.imshow(im, aspect='auto')
xlim, ylim = plt.xlim(), plt.ylim()

Then set them:

plt.plot(x,y, "o")
plt.xlim(xlim)
plt.ylim(ylim)

That should remove the whitespace.

To set the size of the final figure saved, you can pass figsize=(w,h) (size in inches) to savefig, along with dpi (for dots per inch) to determine the final image size. If you are looking for a specific pixel size you can calculate this by wdpi, hdpi.

plt.savefig('dybala.png', figsize=(8,6), dpi=200)

This gives a (8in x 6in)*200 = 1600 x 1200 pixel image in PNG format. However, note that if you use bbox_inches='tight' to remove whitespace around the figure, this happens after the sizing, and will return a smaller image.

You can work around this somewhat by removing the figure axes with plt.axis('off'). If you set the DPI to match that of the source image and scale the figsize accordingly, you should be able to save with bbox_inches='tight' and return an image matching the original dimensions.

Community
  • 1
  • 1
mfitzp
  • 15,275
  • 7
  • 50
  • 70