Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:ax.text未在保存的PDF中显示_Python_Matplotlib - Fatal编程技术网

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

Python:ax.text未在保存的PDF中显示,python,matplotlib,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.

我在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中的文本?

该代码是基于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()

jupyter笔记本中显示的图形是保存的png图像。它们通过选项
bbox\u inches=“tight”
保存

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

plt.savefig('sin.pdf', bbox_inches="tight")
原因是坐标(8,0.9)在图形外部。因此文本不会出现在保存的版本中(也不会出现在交互式图形中)。选项
bbox\u inches=“tight”
扩展或缩小保存的范围,以包括画布的所有元素。使用此选项确实有助于轻松包含绘图之外的元素,而不必关心图形大小、边距和坐标

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

ax.text(1.1, .9, 'Some Text Here', va="top", transform=ax.transAxes)
使其始终位于相对于轴的位置
(1.1.9)

文本坐标(8,0.9)不在我猜想的图形显示范围内。