文字标题未出现matplotlib

pwp*_*rnt 4 python matplotlib legend caption

我不明白为什么我的文字标题没有出现在我的绘图上。我发现文档中关于图例和标题标签的放置顺序非常混乱。

我的代码在这里,我不知道出了什么问题。除了标题的文本根本没有,一切都按我期望的显示(标题,轴标签,日期格式等)。

fig = plt.figure(figsize=(24, 12), dpi=60)
ax = fig.add_subplot(111)
plt.plot(datetime_series,ws_cumsum_mean1,label='1979-1994')
plt.plot(datetime_series,ws_cumsum_mean2,label='1996-2005')
plt.plot(datetime_series,ws_cumsum_mean3,label='2006-2014')
txt = '''Caption text'''
plt.legend(loc='best')
Run Code Online (Sandbox Code Playgroud)

这是我尝试添加标题的地方:

ax.text(0.5,-0.5,txt,transform=ax.transAxes)
Run Code Online (Sandbox Code Playgroud)

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m'))
plt.ylabel('Y label title')
plt.xlabel('X label title')
plt.title('Plot title')
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 6

使用 ax.text(0.5,-0.5,txt,transform=ax.transAxes)该命令将文本放置(0.5,-0.5)在轴坐标中的位置。轴坐标范围从(0,0)(左下角)到(1,1)右上角。(0.5,-0.5)因此,它位于轴的外部,在这种情况下也位于图形的外部。在此处输入图片说明

您可以为y坐标尝试使用介于0到-0.1之间的数字,以查看适合您的需求。或者,使用图形坐标代替坐标轴,并将文本放置在y = 0,处ax.text(0.5,0,txt,transform=fig.transFigure)