lmum27 lmum27 - 1 year ago 172
Python Question

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

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

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

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
to render as a mathematical expression versus a string would be immensely appreciated.

Answer Source

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

The only math you had in your example was the r^2. Below is the image rendered.

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download