Python:ax.text在保存的PDF中未显示

6

我正在ipython笔记本中创建一张带有文本的图表(例如这里的正弦曲线,并在旁边加上一些文本)。在我的笔记本中,图表和文本会同时显示,但是当我保存图表时,只会看到图表而没有文本。我用以下示例代码重现了这个问题:

import numpy as np
import matplotlib.pyplot as plt

fig,ax = plt.subplots(1)
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
ax.plot(x, y)
ax.text(8,0.9,'Some Text Here',multialignment='left', linespacing=2.)
plt.savefig('sin.pdf')

我该如何查看已保存的pdf文件中的文本?

文本坐标(8,0.9)不在图形的显示范围内,我猜测。 - Christian K.
2个回答

5
在jupyter notebook中显示的图形是保存为png图像的。它们是使用选项bbox_inches="tight"保存的。
为了生成与笔记本中的png完全相同的pdf,您还需要使用此选项。
plt.savefig('sin.pdf', bbox_inches="tight")

由于坐标点(8,0.9)在图形之外,所以文本不会出现在保存的版本中(在交互式图中也不会出现)。选项bbox_inches="tight"扩展或缩小保存的范围,以包括画布的所有元素。使用此选项确实很有用,可以轻松地包含位于绘图之外的元素,而无需关心图形大小、边距和坐标。
最后要注意的是:您正在指定文本的位置数据坐标。这通常是不希望的,因为它使文本的位置依赖于在轴中显示的数据。相反,将其指定为轴坐标是有意义的。
ax.text(1.1, .9, 'Some Text Here', va="top", transform=ax.transAxes)

使其始终相对于轴处于位置(1.1,.9)


-1

这段代码是一个完整的工作示例,基于OPs的问题。根据其他用户之前的评论,答案已经进行了更新和修改。内联注释解决了问题所在。

import numpy as np
import matplotlib.pyplot as plt

from matplotlib.font_manager import FontProperties
from matplotlib.backends.backend_pdf import PdfPages

# add filename at start prevents confusion lateron.
with PdfPages('Sin.pdf') as pdf:    

    fig,ax = plt.subplots()
    x = np.linspace(0, 2*np.pi, 100)
    y = np.sin(x)
    ax.plot(x, y)

    # ax.text : 8 > 0.8 and 0.9 => 0.5 keeps text under parabola inside the grid. 
    ax.text(0.8, 0.5, 'Some Text Here', linespacing=2, fontsize=12, multialignment='left')   

    # example of axis labels.
    ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='Sin-wave') 

    ax.grid()

    # you can add a pdf note to attach metadata to a page
    pdf.attach_note("plot of sin(x)", positionRect=[-100, -100, 0, 0])

    # saves the current figure into a pdf page    
    plt.savefig(pdf, format = 'pdf')
    plt.close()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接