我希望使用 annotate() 在 Matplotlib 图中显示一些文本,并在图例框下方对齐。我已经检查了中提出的解决方案如何在 matplotlib 中将文本框直接放置在图例下方? https://stackoverflow.com/questions/42299383/how-to-place-a-text-box-directly-below-legend-in-matplotlib/49314045#49314045并且可以做出适合我的情况的调整,但是添加额外的轴等对于我的情况来说似乎有点过分了。我只是想放置一个注释,其右上角位于图例框右下角下方 20 像素处。
我还希望保存该图的 PDF 文件。
这是我的代码。
import matplotlib.pyplot as plt
import matplotlib.text
fig, ax = plt.subplots()
ax.plot([5,1], label="Label 1")
ax.plot([3,0], label="Label 2")
legend = ax.legend(loc="upper right")
# Create offset from lower right corner of legend box,
# (1.0,0) is the coordinates of the offset point in the legend coordinate system
offset = matplotlib.text.OffsetFrom(legend, (1.0, 0.0))
# Create annotation. Top right corner located -20 pixels below the offset point
# (lower right corner of legend).
ax.annotate("info_string", xy=(0,0),size=14,
xycoords='figure fraction', xytext=(0,-20), textcoords=offset,
horizontalalignment='right', verticalalignment='top')
# Draw the canvas for offset to take effect
fig.canvas.draw()
fig.savefig('plot1.png')
fig.savefig('plot1.pdf')
plt.show()
当该图首次显示时,它看起来是正确的,信息文本正确位于图例下方。此外,保存的 png 文件也能正确显示。但是,pdf 输出中缺少文本。
不知道是不是我的理解有偏差,或者有什么问题。谁能解释一下为什么 pdf 输出不正确?
PNG输出
pdf输出
(matplotlib=2.2、python=2.7.13、Windows 7)