Matplotlib图像适合等式?

时间:2013-06-10 09:26:15

标签: python matplotlib

我使用matplotlib输出方程图像,但我希望图形大小适合公式,如何调整它?

谢谢,

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')

1 个答案:

答案 0 :(得分:1)

由于您要保存表示字符串的数字,因此最好删除黑框框并使背景透明,这可以通过添加这两行来完成,

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

要使图形大小符合公式,请以这种方式保存图形,

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

最后,最好在保存后从内存中删除数字,这是通过添加此行来完成的,

plt.close()

所以新代码将是,

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()

使用上面的新方法,如果执行,  convert('y=3333333333333333333333333333333x') 你应该得到以下结果,

enter image description here

如果运行命令,该图也适合高度

    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')

这个数字将是,

enter image description here