python - Matplotlib 不全屏保存图像

标签 python image matplotlib

[编辑] 正如答案中的评论所建议的,该问题可能与操作系统有关。我在 Windows 10 上。我有 python 3.7.1,我使用 Anaconda/Spyder。
我关注了 thisthis主题尝试在保存之前最大化由绘图生成的图像。在我的代码中,有效的是来自 spyder figure viewer 的图确实最大化了。但是当文件保存成图片时,图片是不是 最大化。
我该如何解决?
我的代码如下:

import matplotlib as mpl
mpl.use('TkAgg') # With this line on: it returns me error. Without: image don't save as it has been shown in plot from spyder.
from datetime import datetime
import constants
import numpy as np
from numpy import *
from shutil import copyfile
from matplotlib.pyplot import *
mpl.rcParams['text.usetex'] = True
mpl.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}']
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cbook as cbook
import matplotlib.gridspec as gridspec

plt.rcParams['lines.linewidth'] = 3
plt.rcParams.update({'font.size': 60})
plt.rc('axes', labelsize=80)
plt.rc('xtick', labelsize=80) 
plt.rc('ytick', labelsize=60) 
rcParams["savefig.jpeg_quality"] = 40 

dpi_value = 100
mpl.rcParams["savefig.jpeg_quality"] = dpi_value
plt.rc('axes', labelsize=60)
plt.rc('xtick', labelsize=60)
plt.rc('ytick', labelsize=60)

def plot_surface(zValues,xValues,yValues,title,xLabel,yLabel,titleSave,xlog=True,ylog=True,zlog=True):
    # This function plots a 2D colormap.
    # We set the grid of temperatures
    X,Y =np.meshgrid(xValues,yValues)
    zValues=np.transpose(np.asarray(zValues))
    # We need to transpose because x values= column, y values = line given doc
    # We now do the plots of kopt-1
    fig1,ax1=plt.subplots()
    if zlog==True:
        pcm1=ax1.pcolor(X,Y,zValues,
                        cmap='rainbow',
                        edgecolors='black',
                        norm=colors.LogNorm(vmin=zValues.min(), vmax=zValues.max()))
    else:
        pcm1=ax1.pcolor(X,Y,zValues,
                        cmap='rainbow',
                        edgecolors='black',
                        norm=colors.Normalize(vmin=zValues.min(),vmax=zValues.max()))
    if xlog==True:
        ax1.set_xscale('log', basex=10)
    if ylog==True:
        ax1.set_yscale('log', basey=10)
        
    ax1.set_title(title)
    ax1.set_ylabel(yLabel)
    ax1.set_xlabel(xLabel)
    
    plt.colorbar(pcm1,extend='max')
    
    figManager = plt.get_current_fig_manager()
    figManager.full_screen_toggle()
    # the solution here 
    plt.tight_layout()
    plt.show()

#    if(constants.save_plot_calculation_fct_parameter==True):
    dpi_value=100
    fig1.savefig(titleSave+".jpg",format='jpg',dpi=dpi_value,bbox_inches='tight')

x=np.arange(0,40)
y=np.arange(0,40)
z=np.random.rand(len(x),len(y))
plot_surface(z,x,y,"AA","BB","CC","name",zlog=False)

plt.show()
来自spyder的渲染图:
enter image description here
并从保存的图像:
enter image description here
[编辑]
我从下面的答案中复制粘贴了代码,但显示仍然不同。来自 spyder 的“图形”窗口:
enter image description here
我电脑上保存的图片:
enter image description here
[新编辑]:我在下面的答案的帮助下列出了所有有效的后端。它们如下:
valid backends:         ['agg', 'nbagg', 'pdf', 'pgf', 'ps', 'qt5agg', 'svg', 'template', 'webagg'] 
唯一可以在 spyder 中显示图形的是 qt5agg。有了这个,图像没有按照解释正确保存。

最佳答案

解决方法是添加plt.tight_layout()就在之前 plt.show .
运行下面的代码 (请注意,在我的 Mac 上,我必须使用 figManager.full_screen_toggle() 而不是 figManager.window.showMaximized() )

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cbook as cbook
import matplotlib.gridspec as gridspec

# comment this part
plt.rcParams['lines.linewidth'] = 3
plt.rcParams.update({'font.size': 20})
#plt.rc('axes', labelsize=60)
#plt.rc('xtick', labelsize=60)
#plt.rc('ytick', labelsize=60)
#rcParams["savefig.jpeg_quality"] = 40

# I don't have the file so I commented this part
# mpl.rcParams['text.usetex'] = True
# mpl.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}']

def plot_surface(zValues,xValues,yValues,title,xLabel,yLabel,titleSave,xlog=True,ylog=True,zlog=True):
    # This function plots a 2D colormap.
    # We set the grid of temperatures
    X,Y =np.meshgrid(xValues,yValues)
    zValues=np.transpose(np.asarray(zValues))
    # We need to transpose because x values= column, y values = line given doc
    # We now do the plots of kopt-1
    fig1,ax1=plt.subplots()
    if zlog==True:
        pcm1=ax1.pcolor(X,Y,zValues,
                        cmap='rainbow',
                        edgecolors='black',
                        norm=colors.LogNorm(vmin=zValues.min(), vmax=zValues.max()))
    else:
        pcm1=ax1.pcolor(X,Y,zValues,
                        cmap='rainbow',
                        edgecolors='black',
                        norm=colors.Normalize(vmin=zValues.min(),vmax=zValues.max()))
    if xlog==True:
        ax1.set_xscale('log', basex=10)
    if ylog==True:
        ax1.set_yscale('log', basey=10)
        
    ax1.set_title(title)
    ax1.set_ylabel(yLabel)
    ax1.set_xlabel(xLabel)
    
    plt.colorbar(pcm1,extend='max')
    
    figManager = plt.get_current_fig_manager()
    figManager.full_screen_toggle()
    # the solution here 
    plt.tight_layout()
    plt.show()

#    if(constants.save_plot_calculation_fct_parameter==True):
    dpi_value=100
    fig1.savefig(titleSave+".jpg",format='jpg',dpi=dpi_value,bbox_inches='tight')

x=np.arange(0,40)
y=np.arange(0,40)
z=np.random.rand(len(x),len(y))
plot_surface(z,x,y,"AA","BB","CC","name",zlog=False)

plt.show()
保存的图像将与弹出的图形相同。

更新
似乎字体大小之间的差异是由 matplotlib backend 引起的您正在使用。基于 this post , 也许尝试另一个后端会解决这个问题 .例如,在我的 Mac 上,如果我使用 TkAgg后端由
import matplotlib as mpl
mpl.use('TkAgg')
弹出屏幕中的数字与保存的数字不同。为了知道哪些可用matplotlib backend在您的机器上,您可以使用
from matplotlib.rcsetup import all_backends   
all_backends是所有可用的列表 backend你可以试试。

更新 2
基于 this wonderful post ,支持的后端不同于有效的后端。为了找到所有可以使用的有效后端,我修改了该帖子中的脚本,
import matplotlib.backends
import matplotlib.pyplot as plt
import os.path


def is_backend_module(fname):
    """Identifies if a filename is a matplotlib backend module"""
    return fname.startswith('backend_') and fname.endswith('.py')

def backend_fname_formatter(fname): 
    """Removes the extension of the given filename, then takes away the leading 'backend_'."""
    return os.path.splitext(fname)[0][8:]

# get the directory where the backends live
backends_dir = os.path.dirname(matplotlib.backends.__file__)
# filter all files in that directory to identify all files which provide a backend
backend_fnames = filter(is_backend_module, os.listdir(backends_dir))
backends = [backend_fname_formatter(fname) for fname in backend_fnames]

print("supported backends: \t" + str(backends),'\n')

# validate backends
backends_valid = []
for b in backends:
    try:
        plt.switch_backend(b)
        backends_valid += [b]
    except Exception as e:
        print('backend %s\n%s\n' % (b,e))
        continue
print("valid backends: \t" + str(backends_valid),'\n')
运行这个脚本,打印出来的后端 valid backends是那些可以应用的。 对于那些支持但无效的后端,也会打印出它们无效的原因。例如,在我的 Mac 上,虽然 wxcairo是受支持的后端,它无效,因为 No module named 'wx' .
通过在您的 PC 上运行脚本找到所有有效的后端后,您可以一一尝试它们,也许其中一个会产生所需的输出图。

关于python - Matplotlib 不全屏保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64612733/

相关文章:

java - 打印屏幕期间的噪音

css - 图像和表格在一行

python - python 2、matplotlib 1.1.1 中的 pylab.ion() 以及在程序运行时更新绘图

python - Matplotlib - 2 Figures in Subplot - 1 is Animation

python - Matplotlib:指定直方图刻度标签中 bin 值的格式

python - Range() 包括其正向和负向步长的界限

python - 如何使用我设置的模型创建此对象?

Javascript:如何交换两个图像的值?

python - 在 Dataframe 中的特定位置添加列

python - 如何判断我的指数曲线在 SciPy 中的拟合效果如何?