簡體   English   中英

渲染matplotlib數學方程

[英]rendering matplotlib mathematical equations

我正在使用Seaborn(用於繪制)和Statsmodels(用於收集系數)的組合來創建回歸圖。 繪圖功能工作正常,但我嘗試使用ax.text()功能將線性回歸方程添加到繪圖中。 但是,我很難使方程式正確渲染。

我咨詢了兩個不同的文檔,但是我發現這些文檔比有用的文檔更令人困惑: 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')

這是因為我在'$'字符中使用'%'字符導致顯示錯誤嗎? 還是有我忘記逃脫的角色? 我們非常感謝我將ax.text()呈現為數學表達式而不是字符串的任何幫助。

您需要在等式周圍使用$...$ 這樣

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

您的示例中僅有的數學是r^2 下面是渲染的圖像。

在此處輸入圖片說明

我可以通過定義一個將浮點數轉換為乳膠可讀格式的函數來獲得所需的最終結果,我從這里開始進行了改編。

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

然后使用以下順序標記每個回歸:

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

也許不是最優雅的解決方案,但足夠了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM