Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine sympy and matplotlib plots in one picture

I need to build an expression graph and a graph set by an array of points, and return the images. To build an expression graph, I use sympy.plot, and to build a graph on points I use matplotlib.

Here is an example code:

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 are generators. How can I combine these images at one?

like image 954
R. Rustan Avatar asked Nov 08 '22 06:11

R. Rustan


1 Answers

I found a solution. Sympy has a method for plotting points. You need to create a List2DSeries object that does the necessary and add to the other graphics using the append method. The resulting code is shown below.

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
like image 107
R. Rustan Avatar answered Nov 13 '22 05:11

R. Rustan