简体   繁体   English

渲染matplotlib数学方程

[英]rendering matplotlib mathematical equations

I am working to create a regression plot using a combination of Seaborn (to plot) and Statsmodels (to collect coefficients). 我正在使用Seaborn(用于绘制)和Statsmodels(用于收集系数)的组合来创建回归图。 The plotting function works fine, but I am attempting to add the linear regression equation to my plot using the ax.text() feature. 绘图功能工作正常,但我尝试使用ax.text()功能将线性回归方程添加到绘图中。 However, I am having trouble getting the equation to render properly. 但是,我很难使方程式正确渲染。

I have consulted two different docs, but I find these more confusing than helpful: http://matplotlib.org/users/usetex.html and http://matplotlib.org/users/mathtext.html#mathtext-tutorial 我咨询了两个不同的文档,但是我发现这些文档比有用的文档更令人困惑: http : //matplotlib.org/users/usetex.htmlhttp://matplotlib.org/users/mathtext.html#mathtext-tutorial

regList = (df.ratiojnatoawd,testDF.ratiojnatoawd, df.ratiopdrtoawd,testDF.ratiopdrtoawd,df.ratiopdrtojna,testDF.ratiopdrtojna)
fig, axs = plt.subplots(3, 2, sharex=True, figsize=(10,6.5))
fig.subplots_adjust(wspace=0.25)

for reg, ax, lims, color in zip(regList, axs.flatten(), axlims, ('g', 'b', 'g','b', 'g','b')):
    regmax = reg.max()
    regmin = reg.min()
    regx = sm.add_constant(np.arange(1,97))
    regy = reg
    regr = sm.OLS(regy, regx).fit()
    label = 'y = %.2ex + %.2e\nr^2 = %.3f' % (regr.params[1], regr.params[0], regr.rsquared)
    sns.regplot(np.arange(1,97), reg,  ax=ax, color=color, scatter_kws={"alpha": 0.35})
    ax.text(0.98,0.75,label, transform=ax.transAxes, horizontalalignment = 'right', bbox=dict(facecolor='w', alpha=0.5))
    ax.yaxis.set_major_formatter(percentFormatter)
    ax.set_ylim(lims)
    ax.set_xlim((0,96))
    ax.set_ylabel('')

axs[0][0].set_ylabel('JnA to Total Awds')
axs[1][0].set_ylabel('PDR to Total Awds')
axs[2][0].set_ylabel('PDR to Total JnA')

Is this rendering incorrectly because I am using '%' characters within the '$' characters? 这是因为我在'$'字符中使用'%'字符导致显示错误吗? Or are there characters I am forgetting to escape? 还是有我忘记逃脱的角色? Any help in getting my ax.text() to render as a mathematical expression versus a string would be immensely appreciated. 我们非常感谢我将ax.text()呈现为数学表达式而不是字符串的任何帮助。

You need to use $...$ around your equation. 您需要在等式周围使用$...$ As this 这样

import matplotlib.pyplot as plt
f, ax = plt.subplots(1,1)
#                           v  v   <-------- These two $-signs
label = 'y = %.2ex + %.2e\nr$^2$ = %.3f' % (10, 100, 0.01)
ax.text(0.5, 0.5, label, horizontalalignment = 'right', bbox=dict(facecolor='w', alpha=0.5))
plt.show()

The only math you had in your example was the r^2 . 您的示例中仅有的数学是r^2 Below is the image rendered. 下面是渲染的图像。

在此处输入图片说明

I was able to get the desired end result by defining a function to convert a float into a latex readable format, which I adapted from here . 我可以通过定义一个将浮点数转换为乳胶可读格式的函数来获得所需的最终结果,我从这里开始进行了改编。

def latex_float(f):
    float_str = "{0:.3g}".format(f)
    if "e" in float_str:
        base, exponent = float_str.split("e")
        return r"{0}e^{{{1}}}".format(base, int(exponent))
    else:
        return float_str

Then labeling each regression using the below sequence: 然后使用以下顺序标记每个回归:

label = '$y = ' +latex_float(regr.params[1])+'x + '+latex_float(regr.params[0])+ '$\n$r^2 = %.3f$' %  (regr.rsquared)

Perhaps not the most elegant solution, but adequate nonetheless 也许不是最优雅的解决方案,但足够了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM