gpt4 book ai didi

python - 使用 python-pptx 将 matplotlib 图形保存在 ppt 文件中,而不保存图形

转载 作者:行者123 更新时间:2023-11-30 22:37:30 24 4
gpt4 key购买 nike

有没有办法使用 python-pptx 在 powerpoint 演示文稿中绘制 matplotlib 图形,而不将图形保存为 *.jpg 或 *.png ?下面是一种简单的方法,即将 matplotlib 图保存为图像文件,然后将其加载到 python-pptx 中,但这根本不是有效的方法。

import numpy as np
import matplotlib.pyplot as plt
from pptx import Presentation
from pptx.util import Inches

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")
plt.plot([70, 70], [100, 250], 'k-', lw=2)
plt.plot([70, 90], [90, 200], 'k-')

plt.show()
plt.savefig('graph.jpg')
img = 'graph.jpg'
prs = Presentation()
title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layout)
pic = slide.shapes.add_picture(img, Inches(1), Inches(1), height=Inches(1))

最佳答案

绘图可以保存为内存中的类似文件对象 (BytesIO),然后传递给 python-pptx:

import io

image_stream = io.BytesIO()
plt.savefig(image_stream)
pic = shapes.add_picture(image_stream, x, y, cx, cy)

关于python - 使用 python-pptx 将 matplotlib 图形保存在 ppt 文件中,而不保存图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43875424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com