【问题标题】:Plot multiple separate figures using matplotlib in pylatex在 pylatex 中使用 matplotlib 绘制多个单独的图形
【发布时间】:2019-11-26 17:25:15
【问题描述】:

我正在尝试使用 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 中绘制单独图的搜索都建议使用子图,这在此处并不适用。

感谢您的帮助。

【问题讨论】:

  • 可能在附加第一个情节后使用plt.clf()?当您使用 plt.show() 时,绘图会自动清除,但是当您在文档中使用它时,matplotlib 不知道何时清除它。
  • @JohanC 效果很好!谢谢你的帮助!!

标签: python matplotlib pylatex


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 2019-09-28
    • 2019-06-24
    • 1970-01-01
    相关资源
    最近更新 更多