我的python代码中有一个奇怪的行为,我在其中绘制一个条形图,它将在一个窗口中显示,但按下" save" -button什么都不做,而.savefig()创建一个0KB的空文件。
更奇怪的是,我在条形图之前有一个for循环,它创建了几个复杂的图,所有这些图都可以绘制然后保存,除了仅绘制的条形图。
我没有从python-console收到任何错误。
这是我在条形图之前的情节循环中的代码:
for l in range(NumberOfResults):
plottitle=groupLimits[0][l+1]+' - Result Width and Probability Distribution of ' + str(numberCombinations) + ' possible Combinations'
fig=plt.figure(plottitle,figsize=(GetSystemMetrics(0)/96,GetSystemMetrics(1)/96),dpi=96)
plt.clf()
ax=fig.add_subplot(1,1,1)
ResultColumn=range(NumberOfInputs,NumberOfInputs+NumberOfResults)[l]
positions=range(len(groupResults))
#positions=list(map(int, np.array(groupLimits[1:])[:,0]))
#plt.grid(1)
y1=[]
x1=[]
for i in range(len(groupResults)):
y1.append(groupResults[i][:,ResultColumn])
x1.append([positions[i]]*len(groupResults[i]))
y=list(np.array(y1).flatten())
s=[]
for i in range(len(groupResults)):
smin=min(groupResults[i][:,ProbabilityColumn])
smax=max(groupResults[i][:,ProbabilityColumn])
s.append((groupResults[i][:,ProbabilityColumn]-smin)/(smax-smin)*25000)
plt.scatter(x1,y1,s=s,marker='_',color='cyan',alpha=0.45)
bp=plt.boxplot(y1, positions=positions, widths=0.5,
labels=list(np.array(groupLimits[1:])[:,0]),
patch_artist=True,whis=[0,100])
#plt.xlim(min(positions)*0.9,max(positions)*1.1)
ax.xaxis.set_tick_params(labelsize=24)
ax.xaxis.grid(True,'major',color='k', linestyle='-', linewidth=0.75)
ax.xaxis.grid(True,'minor',color='k', linestyle=':', linewidth=0.25)
ax.xaxis.set_minor_locator(MultipleLocator(50));
ax.yaxis.set_tick_params(labelsize=24)
ax.yaxis.grid(True,'major',color='k', linestyle='-', linewidth=0.25)
ax.yaxis.grid(True,'minor',color='k', linestyle=':', linewidth=0.25)
ax.yaxis.set_minor_locator(MultipleLocator(0.1));
ax.yaxis.set_ticks(np.arange(int(min(y)),int(max(y))*1.1,0.5))
## change outline color, fill color and linewidth of the boxes
for box in bp['boxes']:
# change outline color
box.set( color='blue', linewidth=3)
# change fill color
box.set( facecolor = 'None')
## change color and linewidth of the whiskers
for whisker in bp['whiskers']:
whisker.set(color='blue', linewidth=3)
## change color and linewidth of the caps
for cap in bp['caps']:
cap.set(color='blue', linewidth=3,alpha=0.8)
## change color and linewidth of the medians
for median in bp['medians']:
median.set(color='magenta', linewidth=3)
y2=[]
x2=[]
for i in range(1,len(groupResults)+1):
if groupLimits[i][l+1]=='-':
pass
else:
y2.append(float(groupLimits[i][l+1]))
if FailedCombinations[i-1][l] is None:
failureString = 'No Results below the Limit'
else:
failureString= str(len(FailedCombinations[i-1][l]))+' failed @ ' + "{:.3g}".format(FailureProbability[i-1][l]*100) + '%'
plt.text(positions[i-1],float(groupLimits[i][l+1])*0.9,
failureString,fontsize=18,horizontalalignment='center',
bbox=dict(facecolor='yellow', edgecolor='black'))
x2.append(positions[i-1])
plt.plot(x2,y2,marker='x',color='red', mew=4,ms=15,linestyle='None')
blue_patch = mpatches.Patch(color='blue', label='Result width')
red_patch = mlines.Line2D([],[],marker='x',color='red', mew=4,ms=15,linestyle='None', label='Limit')
magenta_patch = mpatches.Patch(color='magenta', label='Median')
cyan_patch = mpatches.Patch(color='cyan', label='Probability of Result')
plt.legend(handles=[blue_patch, red_patch, magenta_patch, cyan_patch],
loc='upper left',ncol=1,fontsize=24)
plt.title(plottitle,fontsize=24)
plt.xlabel('Engine Rotation Speed [rpm]',fontsize=24)
plt.ylabel('Absolute Pressure [bar]',fontsize=24)
labelsize = 24
rcParams['xtick.labelsize'] = labelsize
rcParams['ytick.labelsize'] = labelsize
plt.savefig(plottitle)
plt.show()
在我之间运行一些计算来为条形图绘制数据。但是,条形图的代码是:
# Plot group-wise combined failures with all-combined failures at end
plottitle = 'Failed combinations per group - and engine-all combined - TOTAL combinations: ' + str(len(groupResults[0]))
plt.figure(plottitle,figsize=(GetSystemMetrics(0)/96,GetSystemMetrics(1)/96),dpi=96)
plt.clf()
ax=plt.subplot(1,1,1)
y=[]
ind = np.arange(len(groupFailureProbabilities))
for i in range(len(groupFailures)):
y.append(len(groupFailures[i]))
y=tuple(y)
for i in range(len(y)):
if y[i]==0:
pass
else:
string=str(y[i])+' failed @ ' + "{:.3g}".format(groupFailureProbabilities[i]*100)+' %'
plt.text(ind[i],y[i]+100,
string,fontsize=18, horizontalalignment='center',
bbox=dict(facecolor='yellow', edgecolor='black'))
width = 0.35
y=list(y)
plt.bar(ind, y, align='center', color='b')
labels=list(np.array(groupLimits[1:])[:,0])
labels.append('engine \n complete')
ax.set_xticks(ind)
ax.set_xticklabels(tuple(labels))
ax.yaxis.set_tick_params(labelsize=24)
ax.yaxis.grid(True,'major',color='k', linestyle='-', linewidth=0.25)
ax.yaxis.grid(True,'minor',color='k', linestyle=':', linewidth=0.25)
ax.yaxis.set_ticks(np.arange(int(min(y)),int(max(y))*1.1,500))
plt.title(plottitle,fontsize=24)
plt.xlabel('Engine Rotation Speed [rpm]',fontsize=24)
plt.ylabel('Number of Failed Combinations',fontsize=24)
plt.savefig(plottitle)
plt.show()
我无法保存条形图的原因是什么?
答案 0 :(得分:0)
如果我不知道为什么它会在第一时间发生,那么编写重现问题所需的最短代码有点困难。
然而,我设法让它重新安排代码行:
plottitle = 'Failed combinations per group - TOTAL combinations ' + str(len(groupResults[0]))
plt.figure(plottitle,figsize=(GetSystemMetrics(0)/96,GetSystemMetrics(1)/96),dpi=96)
plt.clf()
ax=plt.subplot(1,1,1)
plt.bar(ind, y, align='center')
labels=list(np.array(groupLimits[1:])[:,0])
labels.append('engine \n complete')
ax.set_xticks(ind)
ax.set_xticklabels(tuple(labels))
ax.yaxis.set_tick_params(labelsize=24)
ax.yaxis.grid(True,'major',color='k', linestyle='-', linewidth=0.25)
ax.yaxis.grid(True,'minor',color='k', linestyle=':', linewidth=0.25)
ax.yaxis.set_ticks(np.arange(int(min(y)),int(max(y))*1.1,500))
plt.title(plottitle,fontsize=24)
plt.xlabel('Engine Rotation Speed [rpm]',fontsize=24)
plt.ylabel('Number of Failed Combinations',fontsize=24)
plt.savefig(plottitle+'.png')
plt.show()