1

I would like to export an equation to a PNG image so, for example:

from math import pi, sin

from sympy import init_printing, diff, var, solve
from sympy import sin as sympy_sin
init_printing()

g_v, beta, gamma_a, gamma_b, gamma_c = var("g_v beta gamma_a gamma_b gamma_c")
a, b, c  = var(" a b c")

eq = g_v*sympy_sin(beta)*a*b*c + 2*gamma_a*b*c + 2*gamma_b*a*c + 2*gamma_c*a*b

deq_da = diff(eq, a)
deq_db = diff(eq, b)
deq_dc = diff(eq, c)

solution = solve([deq_da,deq_db,deq_dc],[a,b,c])[1]
solution

I would like to export solution to a PNG image. Like the one below:

enter image description here

There are many other places that kind of address this question. But, they are all unclear, or obsolete. I think the Sympy community would benefit from having a clear best-practice answer to this question.

halfer
  • 19,824
  • 17
  • 99
  • 186
Daniel Marchand
  • 584
  • 8
  • 26

1 Answers1

1

This is somewhat obscure but SymPy's preview function can do this:

with open('solution.png', 'wb') as outputfile:
    preview(solution, viewer='BytesIO', outputbuffer=outputfile)

Behind the scenes this uses LaTeX so you'll need to have that installed and on PATH (specifically it uses latex and dvipng by default).

It would be a reasonable feature request to make the above achievable with something more straight-forward like saveimage(solution, 'solution.png').

Oscar Benjamin
  • 12,649
  • 1
  • 12
  • 14