简体   繁体   English

如何将 sympy 图保存到缓冲区

[英]How to save sympy plot to a buffer

I'm writing an API using fastapi in which there is an endpoint for plotting an arbitrary graph.我正在使用 fastapi 编写一个 API,其中有一个用于绘制任意图的端点。 The client posts the graph equation to the server and the server returns the plot.客户端将图形方程发布到服务器,服务器返回绘图。 This is my current implementation:这是我目前的实现:

import fastapi
import uvicorn
from sympy import plot, parse_expr
from pydantic import BaseModel

api = fastapi.FastAPI()

class Eq(BaseModel):
    eq: str

@api.post('/plot/')
async def plotGraph(eq: Eq):
    exp = parse_expr(eq.eq)
    p = plot(exp, show=False)
    p.save('./plot.png')
    return fastapi.responses.FileResponse('./plot.png')

uvicorn.run(api, port=3006, host="127.0.0.1")

The thing is here i'm saving the plot on the hard drive then reading it again using FileResponse which is kind of redundant.事情就在这里,我将绘图保存在硬盘上,然后使用FileResponse再次读取它,这有点多余。

How to return the underlying image object to the client without the need to writing it to the hard drive first?如何将底层图像对象返回给客户端,而无需先将其写入硬盘?

SymPy uses Matplotlib. SymPy 使用 Matplotlib。 But to achieve your goal you have to either:但要实现您的目标,您必须:

  1. hack your way around with SymPy plotting and use the answer to this question .用 SymPy 绘图破解你的方法并使用这个问题的答案 When you call p.save() , it executes a few important commands.当您调用p.save()时,它会执行一些重要的命令。 Since we don't want to call p.save() we have to execute those commands instead to generate the plot.由于我们不想调用p.save()我们必须执行这些命令来生成绘图。
# after this command, p only contains basic information
# to create the plot
p = plot(sin(x), show=False)
# now we create Matplotlib figure and axes
p._backend = p.backend(p)
# then we populate the plot with the data
p._backend.process_series()

# now you are ready to use this answer:
# https://stackoverflow.com/questions/68267874/return-figure-in-fastapi

# this is how you access savefig
p._backend.fig.savefig
  1. Use Matplotlib directly.直接使用 Matplotlib。 In this case you would have to create a numerical function with lambdify , create an appropriate discretized range with numpy, evaluate the function and create the plot, then use the above-linked answer.在这种情况下,您必须使用lambdify创建一个数值函数,使用 numpy 创建一个适当的离散范围,评估函数并创建绘图,然后使用上面链接的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM