1

I would like to save matplotlib line chart to transparent png image with aspect ratio 3:1 and without axes or labels. I need the line of the graph to start and end directly at the edge of the image (without any padding).

I found several similar topics, e. g. tight savefig without axes in matplotlib or Removing white space around a saved image in matplotlib, however neither advice helped.

Here is my code:

import matplotlib.pyplot as plt

x = np.arange(1, 10)
y = np.arange(51, 60)

plt.gca().set_axis_off()
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
plt.margins(0, 0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())

fig = plt.figure(figsize=(9,3))
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.set_axis_off()

ax.plot(x, y)
# plt.savefig("result.png", format="png", transparent=True, `bbox_inches="tight", pad_inches=0)  # Result image is empty.
plt.savefig("result.png", format="png", transparent=True)
plt.show()

Still, there is some padding in result image (there is white background to show padding, but in fact image is transparent):

enter image description here

Is there any way to achieve chart with no padding?

Michal
  • 1,755
  • 3
  • 21
  • 53

1 Answers1

1

Here is a solution based on one of the question you added:

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

x = np.arange(1, 10)
y = np.arange(51, 60)

plt.figure(figsize=(9,3))
plt.plot(x,y)
plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
            hspace = 0, wspace = 0)
plt.margins(0,0)
plt.savefig("myfig.png")

#os.system('convert myfig.png -trim myfig.png') #<- a quick workaround if you are on mac or Linux.
plt.show()

Output: enter image description here

Grayrigel
  • 3,474
  • 5
  • 14
  • 32
  • Thank you for advice, however there si no aspect ratio 3:1 of result image, so I have to create figure manually. And if I do this, then removing of padding not working anymore. – Michal Sep 24 '20 at 03:43
  • Well, I am not sure what you mean? I had no problem doing this. see my updated answer. – Grayrigel Sep 24 '20 at 08:40
  • 1
    Problem was in wrong order of methods calls. I first set margins and then created figure, which didn't work - my mistake. – Michal Sep 24 '20 at 10:38