gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:12 26 4
gpt4 key购买 nike

我读过类似的 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/

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