Matplotlib的'saveFig()'全屏功能

21
我使用 MatplotLib 和 Cartopy 生成了一些数据图像。 问题在于,当我将框架大小设置为全屏并使用 plt.show() 时,图像完美,并且分辨率很好。
但是,当我使用“plt.savefig()”保存此图时,保存的图像保持其原始大小(不是全屏)。
展示结果图片: 显示图像-不保存 保存图像-不显示 我的代码如下:
def plot_tec_cartopy(descfile): global matrixLon, matrixLat, matrixTec
ax = plt.axes(projection=cartopy.crs.PlateCarree())

v = np.linspace(0, 80, 46, endpoint=True)
cp = plt.contourf(matrixLon, matrixLat, matrixTec, v, cmap=plt.cm.rainbow)
plt.clim(0, 80)
plt.colorbar(cp)

ax.add_feature(cartopy.feature.COASTLINE)
ax.add_feature(cartopy.feature.BORDERS, linestyle=':')
ax.set_extent([-85, -30, -60, 15])

# Setting X and Y labels using LON/LAT format
ax.set_xticks([-85, -75, -65, -55, -45, -35])
ax.set_yticks([-60, -55, -50, -45, -40, -35, -30, -25, -20, -15, -10, -5, 0, 5, 10, 15])
lon_formatter = LongitudeFormatter(number_format='.0f',
                                   degree_symbol='',
                                   dateline_direction_label=True)
lat_formatter = LatitudeFormatter(number_format='.0f',
                                  degree_symbol='')
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)

plt.title('Conteúdo Eletrônico Total', style='normal', fontsize='12')

# Acquiring Date
year, julianday = check_for_zero(descfile.split('.')[2]), descfile.split('.')[3]
hour, minute = descfile.split('.')[4], descfile.split('.')[5].replace('h','')
date = datetime.datetime(int(year), 1, 1, int(hour), int(minute)) + datetime.timedelta(int(julianday)-1)
month = date.month
day = date.day

# Set common labels
ax.text(1.22, 1.05, 'TEC', style='normal',
    verticalalignment='top', horizontalalignment='right',
    transform=ax.transAxes,
    color='black', fontsize=11)
ax.text(1, 0.005, 'EMBRACE/INPE', style='italic',
    verticalalignment='bottom', horizontalalignment='right',
    transform=ax.transAxes,
    color='black', fontsize=10)
ax.text(1, 0.995, str(date) + ' UT', style='italic',
    verticalalignment='top', horizontalalignment='right',
    transform=ax.transAxes,
    color='black', fontsize=10)
ax.text(0.5, -0.08, 'Copyright \N{COPYRIGHT SIGN} 2017 INPE - Instituto Nacional de',
    style='oblique', transform=ax.transAxes,
    verticalalignment='bottom', horizontalalignment='center',
    color='black', fontsize=8)
ax.text(0.5, -0.108, 'Pesquisas Espacias. Todos direitos reservados',
    style='oblique', transform=ax.transAxes,
    verticalalignment='bottom', horizontalalignment='center',
    color='black', fontsize=8)

manager = plt.get_current_fig_manager()
manager.resize(*manager.window.maxsize())

figName = 'tec.map' + '.' + str(year) + '.' + str(julianday) + '.' + str(hour) + '.' + str(minute) + 'h.png'
#plt.show()
plt.savefig(figName, dpi=500)
plt.clf()
也许我需要在savefig()函数中设置一些参数来告诉它保存我的修改后的帧?有人能帮我解决这个问题吗?
提前致谢。

让我猜猜,你是MATLAB用户,希望屏幕上的图形与文件中的图形有所关联? - Mad Physicist
有帮助,但我不认为它是重复的:https://dev59.com/BnRC5IYBdhLWcg3wVvct#4306340。我现在正在起草您的答案。 - Mad Physicist
3个回答

20

如果您之前使用的是MATLAB,那么在Python中,显示的图形与保存的图形在尺寸等方面可能不是一致的,这并不直观。每个图形都有不同的后端进行处理,您可以根据需要修改 dpisize_inches

增加DPI(每英寸点数)肯定会帮助您获得一个较大的图形,特别是对于像PNG这样不知道英寸大小的格式。但是,它将无法相对于图形本身缩放文本。

要实现这一点,您将需要使用对象导向的API,具体来说是figure.set_size_inches,我认为在plt中没有相应的函数。请进行替换。

plt.savefig(figName, dpi=500)

与,用

fig = plt.gcf()
fig.set_size_inches((8.5, 11), forward=False)
fig.savefig(figName, dpi=500)

在美国,8.5, 11是标准纸张尺寸的宽度和高度,您可以将其设置为任何您想要的尺寸。例如,您可以使用屏幕尺寸,但在这种情况下,请确保DPI设置正确。


1
@Hollweg,您可能没有足够的声望来点赞一个答案,但是您可以始终接受对您有益和有用的答案。接受一个问题的答案也会将您的问题从“未回答”列表中移除,因为它应该被解决了。 - swatchai
2
为什么会出现这个错误?AttributeError: 'Figure'对象没有'save'属性。 - Lei Yang
2
@Lei,在新版本中是savefig还是其他什么东西? - Mad Physicist
1
@Shai。看起来在后续版本中,Figure类和pyplot之间的名称已经保持一致了。感谢您的检查。 - Mad Physicist
1
@Shai。我已经更新了。更改是在1.5之前进行的。我猜这是一个相当旧的答案了。 - Mad Physicist
显示剩余3条评论

1

仅为补充@Mad Physicist的答案。如果有人尝试在新版本的matplotlib中使用它,将会出现AttributeError: 'Figure' object has no attribute 'save'。您还需要注意何时调用plt.show(),否则您将得到一张空白图像。您需要按照以下方式更新代码:

# Create a plot
plt.barh(range(top), imp, align='center')
plt.yticks(range(top), names)

# Get the current figure like in MATLAB
fig = plt.gcf()
plt.show() # show it here (important, if done before you will get blank picture)
fig.set_size_inches((8.5, 11), forward=False)
fig.savefig(figName, dpi=500) # Change is over here

希望这有所帮助!

0

我尝试了以上所有答案,似乎不能解决我的问题。也许是因为我在 Mac 上运行,但我找到了解决方法,可以免费尝试。

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

matplotlib.use('TkAgg')

"""work on macos"""


def test():
    x = list(range(10))
    y = list(range(10))
    fig, ax = plt.subplots()
    ax.plot(x, y, linewidth=1.0)

    mng = plt.get_current_fig_manager()
    mng.resize(*mng.window.maxsize())
    figure = plt.gcf()
    plt.show()
    figure.savefig('test.png')


if __name__ == "__main__":
    test()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接