将 sympy 和 matplotlib 绘图合并在一张图片中

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

我需要构建一个表达式图和一个由点数组组成的图,并返回图像。要构建表达式图,我使用

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

x, y 是生成元。如何将这些图像组合在一起?

python matplotlib sympy
3个回答
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

1
投票

有一个解决方案,使用

get_points()
中的
sympy
函数。这是使用 Matplotlib 绘制两组数据的示例

plots = sympy.plot(data0, data1, show=False)
for plot in plots:
   pts = plot.get_points()
   plt.plot(pts[0], pts[1])
plt.show()

您还可以设置

plt
的所有参数,例如轴限制和图例。


0
投票

sympy.plot
具有未注释的参数
fig
ax
,它将采用现有的 matplotlib 图形并用数据填充它。

import matplotlib.pyplot as plt
import sympy

fig, ax = plt.subplots()
ax.scatter([-2,-1,0,1,2], [4.1,0.9,0.1,1.1,3.8])

x = sympy.symbols('x')
sympy.plot(x**2, (x,-2,2), fig=fig, ax=ax)
© www.soinside.com 2019 - 2024. All rights reserved.