简体   繁体   中英

rendering matplotlib mathematical equations

I am working to create a regression plot using a combination of Seaborn (to plot) and Statsmodels (to collect coefficients). The plotting function works fine, but I am attempting to add the linear regression equation to my plot using the ax.text() feature. 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

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.

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 . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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