user326503
user326503

Reputation:

Matplotlib Image fit to equation?

I use matplotlib to output equation image, but I want the figure size fit to the equation, how to adjust it?

Thanks,

import matplotlib.pyplot as plt

def convert(string):
    if string[0] != '$' and string[-1] != '$':
        string = '$' + string + '$'
    plt.text(0.01, 0.8, string, fontsize=50)
    plt.xticks(())
    plt.yticks(())
    plt.savefig('latex.png')

Upvotes: 2

Views: 214

Answers (1)

IssamLaradji
IssamLaradji

Reputation: 6855

Since you are saving a figure that represents a string, it might be better to remove the black frame box and make the background transparent, which is done by adding these two lines,

plt.figure(frameon=False)
plt.axes(frameon=0)

To make the figure size fit the equation, save the figure this way,

plt.savefig('D:/latex.png', bbox_inches='tight')

Finally, its better to remove the figure from memory after saving it, and this is done by adding this line,

plt.close()

So the new code would be,

import matplotlib.pyplot as plt

def convert(string):
    plt.figure(frameon=False)
    plt.axes(frameon=0)
    if string[0] != '$' and string[-1] != '$':
        string = '$' + string + '$'
    plt.text(0.01, 0.8, string, fontsize=50)
    plt.xticks(())
    plt.yticks(())
    plt.savefig('D:/latex.png', bbox_inches='tight')
    plt.close()

With the new method above, if you execute, convert('y=3333333333333333333333333333333x') You should get the following result,

enter image description here

The figure also fits the height, if you run the command,

    convert('y=1x\ny=2x\ny=3x\ny=4x\ny=5x\ny=6x\ny=7x\ny=8x\n
               y=9x\ny=10y\ny=11x\ny=22x\ny=33x\ny=44x\ny=55x\ny=66x\ny=77x')

The figure would be,

enter image description here

Upvotes: 1

Related Questions