如果我 运行 完整的 Python 脚本(matplotlib),Y-tick 标签就会消失

Y-tick labels disappear if I run full Python script (matplotlib)

我正在使用 Spyder (python 2.7),并使用 matplotlib 绘制图形。当我有一大块代码(见下文)时,如果我突出显示并手动执行我的代码,一切看起来都很好。但是,如果我点击完整脚本的 运行 按钮,或者在循环中执行此代码,则 y 刻度标签会从每个图中消失。不能为我的生活找到问题。

data2plot = [120.0, 56.0, 26.0, 11.0, 6.0, 6.0, 5.0, 5.0, 3.0, 3.0, 2.0, 2.0, 2.0]
bar_locs = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0]
x_labs = ['','','','','','','','','','','','','']
fig, ax = plt.subplots()
#plot_help.bigfig()    
rects = ax.bar(bar_locs, data2plot, 0.75, color='steelblue', align='center')                 
ax.set_xticks(bar_locs)
ax.set_xticklabels(x_labs, fontweight='bold', fontsize=13, rotation=-45, ha='left')      
ax.set_xlim(0, len(x_labs)+0.75)
#ax.set_ylim(0, y_max)
ax.set_ylabel('Pageviews', fontweight='bold', fontsize=15)
ax.set_yticklabels(ax.get_yticklabels(), fontweight='bold', fontsize=13)
ax.set_title('Title', fontweight='bold', fontsize=16)    

plt.gcf().subplots_adjust(bottom=0.45)
#plot_help.simpleaxis(ax) 

您遇到的问题在这一行 ax.set_yticklabels(ax.get_yticklabels(), ...)
在您调用 ax.get_yticklabels() 的那一刻,标记标签尚未设置,因此 ax.get_yticklabels() returns 一个空字符串列表。然后将这些空字符串设置为新的 yticklabels。 如果您事先调用 fig.canvas.draw() ,则可以防止这种情况发生。这将绘制图形并初始化刻度标签,以便列表在提供给 setter.

时不会为空字符串

这是完整的代码。

import matplotlib.pyplot as plt

data2plot = [120.0, 56.0, 26.0, 11.0, 6.0, 6.0, 5.0, 5.0, 3.0, 3.0, 2.0, 2.0, 2.0]
bar_locs = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0]
x_labs = ['','','','','','','','','','','','','']

fig, ax = plt.subplots()   
rects = ax.bar(bar_locs, data2plot, 0.75, color='steelblue', align='center')

# x-axis              
ax.set_xticks(bar_locs)
ax.set_xticklabels(x_labs, fontweight='bold', fontsize=13, rotation=-45, ha='left')      
ax.set_xlim(0, len(x_labs)+0.75)

#y-axis
ax.set_ylabel('Pageviews', fontweight='bold', fontsize=15)
fig.canvas.draw()
ax.set_yticklabels(ax.get_yticklabels(), fontweight='bold', fontsize=13)


ax.set_title('Title', fontweight='bold', fontsize=16)    
plt.gcf().subplots_adjust(bottom=0.45)
plt.show()


或者,如果您打算将图中的所有文本、标签和标题都加粗和放大,那么您可以考虑使用 matplotlib rcParams,如下所示。

plt.rc('font', size=13, weight='bold')
plt.rc('figure', titlesize="x-large", titleweight ='bold')
plt.rc("axes", labelsize = "large", labelweight = "bold", titlesize="x-large", titleweight="bold")

data2plot = [120.0, 56.0, 26.0, 11.0, 6.0, 6.0, 5.0, 5.0, 3.0, 3.0, 2.0, 2.0, 2.0]
bar_locs = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0]
x_labs = ['','','','','','','','','','','','','']

fig, ax = plt.subplots()   
rects = ax.bar(bar_locs, data2plot, 0.75, color='steelblue', align='center')

# x-axis              
ax.set_xticks(bar_locs)
ax.set_xticklabels(x_labs, rotation=-45, ha='left')      
ax.set_xlim(0, len(x_labs)+0.75)

#y-axis
ax.set_ylabel('Pageviews')

ax.set_title('Title')    
plt.gcf().subplots_adjust(bottom=0.45)
plt.show()