在一张图片中结合 sympy 和 matplotlib 图

R. *_*tan 5 python matplotlib sympy

我需要构建一个表达式图和一个由点数组设置的图,并返回图像。要构建表达式图,我使用sympy.plot,并在我使用的点上构建图matplotlib

这是一个示例代码:

from os import remove
from matplotlib import pyplot as plt
from PIL import Image
from sympy import plot, symbols

def plot_graphic(x, y, expression, file_name):
    file = '{}.png'.format(file_name)
    x1, y1 = list(x), list(y)
    plt.plot(x1, y1)
    plt.savefig(file)
    plt.close()
    del y1
    img = Image.open(file)
    remove(file)
    yield img

    x = symbols('x')
    plot(expression.args[1], (x, x1[0], x1[-1]), show=False).save(file)
    img = Image.open(file)
    remove(file)
    yield img
Run Code Online (Sandbox Code Playgroud)

x, y 是生成器。如何将这些图像合二为一?

R. *_*tan 1

我找到了解决方案。Sympy 有一种绘制点的方法。您需要创建一个List2DSeries执行必要操作的对象,并使用该append方法添加到其他图形。生成的代码如下所示。

from os import remove
from PIL import Image
from sympy import plot, symbols
from sympy.plotting.plot import List2DSeries

def plot_graphic(x, y, expression, file_name):
    file = '{}.png'.format(file_name)
    x1, y1 = list(x), list(y)
    x = symbols('x')
    graph = plot(expression.args[1], (x, x1[0], x1[-1]), show=False, line_color='r')
    graph.append(List2DSeries(x1, y1))
    graph.save(file)
    img = Image.open(file)
    remove(file)
    return img
Run Code Online (Sandbox Code Playgroud)