首页 > 解决方案 > 在 pylatex 中使用 matplotlib 绘制多个单独的图形

问题描述

我正在尝试使用 pylatex 和 matplotlib 在一个 pdf 中绘制多个不同的图。下面的代码可以很好地生成两个图,但是,当我只想要两个单独的图时,第二个图包含第一个图的数据,即一个图中的 (x,y) 和另一个图中的 (x_1, y_1)。

问题是当我使用plt.plot第二个图时,它会将第二个图的数据添加到第一个图中。

MWE代码:

import matplotlib

from pylatex import Document, Section, Figure, NoEscape

matplotlib.use('Agg')  # Not to use X server. For TravisCI.
import matplotlib.pyplot as plt  # noq

if __name__ == '__main__':

    x = [0, 1, 2, 3, 4, 5, 6]
    y = [15, 2, 7, 1, 5, 6, 9]
    plt.plot(x, y)

    doc = Document('basic')
    doc.append('Introduction.')

    with doc.create(Section('I am a section')):
        doc.append('Take a look at this beautiful plot:')
        with doc.create(Figure(position='htbp')) as plot:
                plot.add_plot(width=NoEscape(r'1\linewidth'), dpi=300)
                plot.add_caption('I am a caption.')

if __name__ == '__main__':

    x_1 = [0, 1, 2, 3, 4, 7, 6]
    y_1 = [15, 2, 5, 1, 5, 6, 9]

    plt.plot(x_1, y_1)

    with doc.create(Section('I am a section')):
        doc.append('Take a look at this beautiful plot:')
        with doc.create(Figure(position='htbp')) as plot3:
                plot2.add_plot(width=NoEscape(r'1\linewidth'), dpi=300)
                plot2.add_caption('I am a caption.')

    doc.append('Conclusion.')

    doc.generate_pdf(clean_tex=False)

我认为这与两个数字的绘图对象相同有关。我不太清楚如何将它们分开,因为大多数在 matplotlib 中绘制单独图的搜索都建议使用子图,这在此处并不适用。

谢谢你的帮助。

标签: pythonmatplotlibpylatex

解决方案


我只是使用 jupyter-notebook,然后将其导出为 html,然后导出为 pdf。麻烦少了很多。


推荐阅读