1

I'm relatively new to Sympy and had a lot of trouble with the information that I was able to scavenge on this site. My main goal is basically to take a string, representing some mathematical expression, and then save an image of that expression but in a cleaner form.

So for example, if this is the expression string: "2**x+(3-(4*9))" I want it to display like this cleaner image.

This is currently the code that I have written in order to achieve this, based off of what I was able to read on StackExchange:

from matplotlib import pylab
from sympy.parsing.sympy_parser import parse_expr
from sympy.plotting import plot
from sympy.printing.preview import preview


class MathString:

    def __init__(self, expression_str: str):
        self.expression_str = expression_str

    @property
    def expression(self):
        return parse_expr(self.expression_str)

    def plot_expression(self):
        return plot(self.expression)

    def save_plot(self):
        self.plot_expression().saveimage("imagePath", 
        format='png')

And then using a main function:

def main():
    test_expression = '2**x+(3-(4*9))'
    test = MathString(test_expression)
    test.save_plot()


main()

However, when I run main(), it just sends me an actual graphical plot of the equation I provided. I've tried multiple other solutions but the errors ranged from my environment not supporting LaTeX to the fact that I am passing trying to pass the expression as a string.

Please help! I'm super stuck and do not understand what I am doing wrong! Given a certain address path where I can store my images, how can I save an image of the displayed expression using Sympy/MatPlotLib/whatever other libraries I may need?

1 Answers1

0

The program in your question does not convert the expression from string format to the sympy internal format. See below for examples.

Also, sympy has capabilities to detect what works best in your environment. Running the following program in Spyder 5.0 with an iPython 7.22 terminal, I get the output in Unicode format.

from sympy import *

my_names = 'x'
x = symbols(','.join(my_names))
ns1 = {'x': x}
my_symbols = tuple(ns1.values())
es1 = '2**x+(3-(4*9))'
e1 = sympify(es1, locals=ns1)
e2 = sympify(es1, locals=ns1, evaluate=False)
print(f"String {es1} with symbols {my_symbols}",
      f"\n\tmakes expression {e1}",
      f"\n\tor expression {e2}")
# print(simplify(e1))
init_printing()
pprint(e2)

Output (in Unicode):

# String 2**x+(3-(4*9)) with symbols (x,)
#   makes expression 2**x - 33
#   or expression 2**x - 4*9 + 3
#  x
# 2  - 4⋅9 + 3
VirtualScooter
  • 1,792
  • 3
  • 18
  • 28
  • I understand how to print expressions to unicode using init_printing. I'm just trying to find a way to export the expression as a png in the style found in the linked image. – TeriyakiNinja Jul 23 '21 at 04:49