尝试将 python matplotlib 绘图插入到 Word 文档表中

问题描述 投票:0回答:1

我的模块创建一个Word文档,然后在该文档中创建一个3列的表格。然后,该模块调用另一个模块中的函数,该函数根据在笛卡尔网格中绘制的随机创建的顶点生成梯形。

我收到错误消息 AttributeError: 'Figure' 对象没有属性 'seek'。最后提供回溯。

成品应该是这样的,是我手动制作的:

主要模块是:

import os
import random
from docx import Document
from docx.shared import Inches
from datetime import datetime
from docx.oxml import OxmlElement, ns
import Trapezoid_in_Cartesian_Grid_1
from PIL import Image


doc = Document()

tbl = doc.add_table(rows=1, cols=0)
tbl.add_column(width=Inches(0.4))
tbl.add_column(width=Inches(3.0))
tbl.add_column(width=Inches(3.0))

for i in range(10):
    a = random.randint(-8,8)
    b = random.randint(-8,8)
    h = random.randint(-3,3)
    k = random.randint(-3,3)
    fig = Trapezoid_in_Cartesian_Grid_1.ReflectTrap01OverXaxis(a,b,h,k)
    
    row = tbl.add_row()
    cell1 = tbl.cell(i,0)
    cell1.text = str(i+1) + "."
    cell2 = tbl.cell(i,1) 
    cell2.text = "Reflect the figure over the y-axis."
    cell3 = tbl.cell(i,2)
    paragraph = tbl.rows[0].cells[2].paragraphs[0]
    run = paragraph.add_run()
    run.add_picture(fig, width=Inches(3.0), height=Inches(3.0))
   
# get current date and time and convert to string
current_datetime = datetime.now().strftime("%Y-%m-%d %H%M%S")
print("Current date & time : ", current_datetime)
str_current_datetime = str(current_datetime)
 
# create a file object along with extension
file_name = "WS_Proj " + str_current_datetime
header = doc.sections[0].header
header.paragraphs[0].text = file_name
footer = doc.sections[0].footer

doc.save(file_name + ".docx")

被调用的模块(带函数)是

from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.path import Path
import matplotlib.patches as patches
from matplotlib.ticker import MultipleLocator
from docx.shared import Inches
import matplotlib.ticker as ticker
import random

a = random.randint(-8,8)
b = random.randint(-8,8)
h = random.randint(1,5)
k = random.randint(1,5)

current_datetime = datetime.now().strftime("%Y-%m-%d %H%M%S")
str_current_datetime = str(current_datetime)

def ReflectTrap01OverXaxis(a,b,h,k):
       
   #Creates a polygon with certain vertices (verts1)
    verts1 = [(a,b),(a+h,b),(a+h,b-k),(a,b-k+1),(a,b)]
    codes1 = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]
    fig = plt.figure()
    ax = fig.add_subplot(111)
    path1 = Path(verts1, codes1)
    patch1 = patches.PathPatch(path1, edgecolor = "black", facecolor = "None", lw=1, zorder = 3)
    ax.add_patch(patch1)
    
   #Sets x and y axes
    ax.set_xlim(-12,12)
    ax.set_ylim(-12,12)
    plt.grid(True)
    plt.tick_params(labelsize = 6)
    plt.xlabel(None, fontsize = 7)
   #Determines the size of the plot
    plt.rcParams["figure.figsize"] = [3.0,3.0]
    
    plt.axhline(color = "black")
    plt.axvline(color = "black")
    
    ax.grid(which = "both",color = "black", linewidth=0.4)
    ax.minorticks_on()
    
   #Creates a unique file name with date and time
    current_datetime = datetime.now().strftime("%Y-%m-%d %H%M%S")
    str_current_datetime = str(current_datetime)
    file_name = "fig1 " + str_current_datetime
    plt.savefig(file_name,dpi = 1200 ,format = "jpg")
    
    return fig
    File ~\anaconda3\Lib\site-packages\spyder_kernels\py3compat.py:356 in compat_exec
    exec(code, globals, locals)

  File c:\users\barry\.spyder-py3\createtablewithspecificdimensions.py:40
    run.add_picture(fig, width=Inches(3.0), height=Inches(3.0))

  File ~\anaconda3\Lib\site-packages\docx\text\run.py:79 in add_picture
    inline = self.part.new_pic_inline(image_path_or_stream, width, height)

  File ~\anaconda3\Lib\site-packages\docx\parts\story.py:71 in new_pic_inline
    rId, image = self.get_or_add_image(image_descriptor)

  File ~\anaconda3\Lib\site-packages\docx\parts\story.py:37 in get_or_add_image
    image_part = package.get_or_add_image_part(image_descriptor)

  File ~\anaconda3\Lib\site-packages\docx\package.py:31 in get_or_add_image_part
    return self.image_parts.get_or_add_image_part(image_descriptor)

  File ~\anaconda3\Lib\site-packages\docx\package.py:74 in get_or_add_image_part
    image = Image.from_file(image_descriptor)

  File ~\anaconda3\Lib\site-packages\docx\image\image.py:49 in from_file
    stream.seek(0)

AttributeError: 'Figure' object has no attribute 'seek'

感谢您的帮助。

python function matplotlib plot
1个回答
0
投票

如果图像标题丢失或损坏,MS Word 显然会出现问题。仅仅添加文件扩展名(例如“jpeg”)是不够的。我在网上找到了这个代码片段,它“修复”了标题。我在调用 ReflectTrap01OverXaxis() 之后立即将此代码片段放入主模块的 for 循环中。

def image_to_jpg(image_path):
path = Path(image_path)
if path.suffix not in {'.jpg', '.png', '.jfif', '.exif', '.gif', '.tiff', '.bmp'}:
    jpg_image_path = f'{path.parent / path.stem}_result.jpg'
    Image.open(image_path).convert('RGB').save(jpg_image_path)
    return jpg_image_path
return image_path

我的程序现在运行正常。

© www.soinside.com 2019 - 2024. All rights reserved.