简体   繁体   中英

How to save a matplotlib.pypot figure as an image with required pixel size?

I have plotted matplotlib.pyplot plot. I have already removed the axes and title of the plot such that in jupyter notebook it looks like an image.

But I need to save that plot as an image to my local disk with required pixel resolution. In my case it's 40 X 98.

I have tried plt.savefig but I can't get the measurements accurately. I have provided my code snippet below. (spectrum) is my 2D array which is to be plotted as a fucntion of x and y axes.

spect = 20 * np.log10(spectrum)
fig, ax = plt.subplots(figsize=(1,1))
ax = sns.heatmap(spect,cmap='viridis',cbar=False,xticklabels=False, yticklabels=False)
ax.invert_yaxis()
plt.savefig('sample.png',bbox_inches = 'tight', pad_inches = 0)

Try adjusting the dpi argument in savefig . From the docs: "dpi: the resolution in dots per inch". https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.savefig.html

The actual number of pixels may vary depending on your screen resolution.

For a more detailed explanation, see this answer: Specifying and saving a figure with exact size in pixels

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM