简体   繁体   English

Python保存带有精确像素大小的matplotlib图

[英]Python save matplotlib figure with exact pixel size

I want to save an matplotlib figure with an exact size in pixels. 我想保存一个精确大小的matplotlib图像。 In the code below, this exact size is 500x500 pixels. 在下面的代码中,这个确切的大小是500x500像素。 Whilst the saved image is 500x500 pixels it includes padding around my shape and plot area. 虽然保存的图像是500x500像素,但它包括我的形状和绘图区域周围的填充。 I want the circle to be tight to the borders. 我希望圆圈紧贴边界。 Instead there is white space around my circle. 相反,我的圈子周围有空白区域。 Is it possible to save the plotting area only? 是否可以仅保存绘图区域? Please note that while the code below is reproducible, my_dpi is dependant upon your monitor DPI. 请注意,虽然下面的代码是可重现的,但my_dpi取决于您的显示器DPI。 220 is my display's DPI. 220是我的显示器的DPI。

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

H       = 500
W       = 500
radius  = H/2
my_dpi  = 220


a = np.deg2rad(0)
b = np.deg2rad(360);

t = np.linspace(a,b,100)
x = radius*np.cos(t)
y = radius*np.sin(t)
x = np.append(x,[0,x[0]])
y = np.append(y,[0,y[0]])

myFig   = plt.figure()
DPI     = my_dpi #myFig.get_dpi()
myFig.set_size_inches(float(H)/float(DPI),float(W)/float(DPI))

plt.fill(y,x,color='none',facecolor='red')
plt.axis((-W/2,W/2,-H/2,H/2))
plt.axis('off')
#plt.show()
plt.savefig('my_fig.png',dpi=DPI)

print 'Figure Size: ', myFig.get_size_inches()

Im = mpimage.imread('my_fig.png')
print 'Im Size: ', Im.shape

You can use subplots_adjust to set the padding around your plot. 您可以使用subplots_adjust在绘图周围设置填充。

myFig.subplots_adjust(bottom=0.,left=0.,right=1.,top=1.)

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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