Skip to main content
 首页 » 编程设计

python之Matplotlib 图像适合方程

2025年05月04日12mfrbuaa

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

请您参考如下方法:

因为你保存的是一个代表字符串的图形,所以最好去掉黑色的框框并使背景透明,这是通过添加这两行来完成的,

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

使用上面的新方法,如果你执行, 转换('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') 

这个数字是,