python - Matplotlib:循环中创建的第一个绘图未使用 rcParams 中指定的 'figsize' 保存

标签 python matplotlib size figure

我读过类似的 Jupyter Notebooks 问题,例如:Matplotlib figsize not respected

我的函数使用 for 循环生成并保存绘图。生成的第一个图总是较小,并且缺乏其他图的格式。如果我运行该函数两次,问题就得到解决。

我尝试指定一个特定的后端:matplotlib.use('Agg'),但这没有效果。

        fig, ax = plt.subplots()
        #Format xlabel and grid
        plt.xlabel('Date', weight = 'bold')
        plt.grid(alpha = 2.0)
        #Clear legend
        legendList = legendList[0:0]
        #Format data to required units and set axis label
        for i in range(len(plotData.columns)):
            plt.ylabel(splitUnits + ' ' + '[' + units + ']', weight = 'bold')
            #Plot each data column on axis
            ax = self.formatAxis(ax)
            ax.plot(plotData.iloc[:,i], formatList[i], linewidth=2, markersize=2)

            #Set Legend and remove brackets from array
            legendList.append(str(plotData.iloc[:,[i]].columns.values[-1]).lstrip('(').rstrip(')')) 

        plt.legend(loc='upper right', labels=legendList)

        #Resize graph and set resolution
        plt.rcParams['figure.figsize'] = (12, 7)        #Width and height of graph 12,7
        dpi = 250    #108 previously
        plt.rcParams['figure.dpi'] = dpi

        plt.rcParams['figure.figsize'] = (12, 7)
        #Format y-axis grid and ticks and legend format
        ax.grid(which='minor', alpha=0.4)     #...alpha controls gridline opacity
        ax.margins(y=0.85)
        ymin = ax.get_yticks()[0]
        ymax = ax.get_ylim()[-1]
        step = ax.get_yticks()[1] - ax.get_yticks()[0]
        y_minor = np.arange(ymin, ymax, step/5)
        ax.set_yticks(y_minor, minor=True)
        ax.set_ylim([ymin, ymax])

        #Import Logo, and insert in graph
        self.manageDir('working')
        im = image.imread('logo4.png')
        fig.figimage(im, 280, 1360, zorder=1)     #130, 580 represent logo placement in graph
        plt.close('all')

        fig.savefig('Plot ' + str(plotNo) + '.png', bbox_inches='tight', pad_inches=0.3)

“PlotData”是一个数据框,其中所有值都绘制在同一轴上,然后保存。保存到文件的第一个图像似乎使用默认的图形大小设置,但保存的所有其他图都使用指定的 (12, 7) 设置。如果有人有任何想法或想要任何信息,请告诉我!谢谢!

最佳答案

存储在 rcParams 中的图形设置在调用 plt.figure()plt.subplots() 时读取。因此,为了使 rcParams 中的设置正常工作,您必须在创建图形之前将这些分配移至。最好的办法是将所有 rcParams 分配移至脚本的开头。

或者,您可以分别使用命令 fig.set_size_inches()fig.set_dpi() 来更改图形大小和分辨率。

关于python - Matplotlib:循环中创建的第一个绘图未使用 rcParams 中指定的 'figsize' 保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54664029/

相关文章:

Python使用apply或map计算NTLM哈希值

c# - 包含 guid 的结构上的 Marshal.SizeOf 提供额外的字节

python - ImportError :libpng16. so.16 无法打开共享对象文件

python - 对于空刻度标签,Matplotlib 鼠标光标坐标不显示

python - 数字作为字符串的 seaborn 色调

size - 更改 QStandardItemModel 中的 QIcon 大小

python - 图像尺寸突然缩小

python - 使用传输编码 Python 时出现 502 Bad gateway

Python ABCs : registering vs. 子类化

python - 如何在 babel.dates.format_date 中将格式设置为小时?