gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:00:41 25 4
gpt4 key购买 nike

我想保存一个以像素为单位的精确大小的 matplotlib 图。在下面的代码中,这个精确大小是 500x500 像素。虽然保存的图像是 500x500 像素,但它包括我的形状和绘图区域周围的填充。我希望圆圈紧贴边界。相反,我的圆圈周围有空白。是否可以只保存绘图区域?请注意,虽然下面的代码是可重现的,但 my_dpi 取决于您的显示器 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

最佳答案

您可以使用 subplots_adjust 设置绘图周围的填充。

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

enter image description here

关于Python 以精确的像素大小保存 matplotlib 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28491314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com