Search code examples
pythonmatplotlibfigure

Save only line without axes, labels and padding in matplotlib


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?


Solution

  • 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