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

时间:2017-12-17 17:40:05

标签: python matplotlib

我正在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中查看文字?

2 个答案:

答案 0 :(得分:2)

jupyter笔记本中显示的数字是保存的png图像。它们使用选项bbox_inches="tight"保存。

为了生成与笔记本中的png完全相同的pdf,您还需要使用此选项。

plt.savefig('sin.pdf', bbox_inches="tight")

原因是坐标(8,0.9)在图的外面。因此,文本不会出现在它的已保存版本中(它也不会出现在交互式图中)。选项bbox_inches="tight"扩展或缩小保存的范围以包括画布的所有元素。使用此选项确实非常有用,可以轻松地包含在绘图之外的元素,而无需关心图形大小,边距和坐标。

最后一点:您正在数据坐标中指定文本的位置。这通常是不希望的,因为它使文本的位置取决于轴中显示的数据。相反,在轴coordiantes中指定它是有意义的,

ax.text(1.1, .9, 'Some Text Here', va="top", transform=ax.transAxes)

这样它总是相对于轴位于(1.1,.9)位置。

答案 1 :(得分:-1)

代码是基于OP问题的完整工作示例。根据其他用户之前的评论,更新和修改答案。内联注释解决了问题的解决方法。

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()