2

我使用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')
4

1 回答 1

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') 你应该得到以下结果,

在此处输入图像描述

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

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

这个数字是,

在此处输入图像描述

于 2013-06-10T14:04:26.177 回答