简体   繁体   English

MatplotLib 'saveFig()' 全屏

[英]MatplotLib 'saveFig()' Fullscreen

I used MatplotLib with Cartopy to generate some data images.我使用 MatplotLib 和 Cartopy 生成了一些数据图像。 The problem is that when I set the frame size to fullscreen and use plt.show() the image is perfect and the resolution is fine.问题是,当我将帧大小设置为全屏并使用 plt.show() 时,图像是完美的,分辨率也很好。

However, when I save this figure using 'plt.savefig()' the image saved keeps with its original size (not fullscreen).但是,当我使用“plt.savefig()”保存此图时,保存的图像保持其原始大小(不是全屏)。

Showing outcome images:显示结果图像:

显示图像 - 不保存

保存图像 - 不显示它

My code is the following:我的代码如下:

def plot_tec_cartopy(descfile): global matrixLon, matrixLat, matrixTec 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()

Maybe I need to set some parameter into savefig() to say it that it needs to save my modified frame?也许我需要在 savefig() 中设置一些参数来说明它需要保存我修改过的帧? Can someone help me with this issue?有人可以帮我解决这个问题吗?

Thanks in advance.提前致谢。

Coming from MATLAB, it is not intuitive that your displayed figure does not have to affect the saved one in terms of dimensions, etc. Each one is handled by a different backend, and you can modify the dpi and size_inches as you choose.来自 MATLAB,您显示的图形不必在尺寸等方面影响保存的图形,这并不直观。每个图形由不同的后端处理,您可以根据自己的选择修改dpisize_inches

Increasing the DPI is definitely going to help you get a large figure, especially with a format like PNG, which does not know about the size in inches.增加 DPI 肯定会帮助您获得较大的数字,尤其是对于像 PNG 这样的格式,它不知道以英寸为单位的大小。 However, it will not help you scale the text relative to the figure itself.但是,它不会帮助您相对于图形本身缩放文本。

To do that, you will have to use the object oriented API, specifically, figure.set_size_inches , which I don't think has an equivalent in plt .为此,您必须使用面向对象的 API,特别是figure.set_size_inches ,我认为它在plt中没有等价物。 Replace代替

plt.savefig(figName, dpi=500)

with

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

The size 8.5, 11 is the width and height of the standard paper size in the US, respectively.尺寸8.5, 11分别是美国标准纸张尺寸的宽度和高度。 You can set it to whatever you want.您可以将其设置为任何您想要的。 For example, you can use your screen size, but in that case be sure to get the DPI right as well.例如,您可以使用您的屏幕尺寸,但在这种情况下,请务必确保 DPI 也正确。

Just to add some context on @Mad Physicist answer.只是为了在@Mad Physicist 答案上添加一些上下文。 If someone is trying to use it with a new version of matplotlib, you will get an AttributeError: 'Figure' object has no attribute 'save'.如果有人试图将它与新版本的 matplotlib 一起使用,你会得到一个 AttributeError: 'Figure' object has no attribute 'save'。 You also need to be careful about when you call plt.show() otherwise you will get a blank image.当你调用plt.show()时你也需要小心,否则你会得到一个空白图像。 You need to update the code as follow:您需要按如下方式更新代码:

# 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

Hope it helps!希望能帮助到你!

I tried all answers above, and didn't seem to solve my problem.我尝试了上面的所有答案,似乎并没有解决我的问题。 Maybe becase I run on Mac, but I figured it out, free to try.也许是因为我在 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()

What I used the most to solve it is to set the figure size to my convenience before plotting the information.我用最多的方法来解决它是在绘制信息之前将图形大小设置为方便。

I use the parameter figsize from the plt.figure to set it up.我使用 plt.figure 中的参数 figsize 来设置它。 Find here some information about it.在这里找到一些关于它的信息。

https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html

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

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