打印最佳拟合线的方程式

时间:2014-04-18 07:06:40

标签: numpy matplotlib

我使用以下代码为数据集创建了最佳拟合线:

fig, ax = plt.subplots()
for dd,KK in DATASET.groupby('Z'):
  fit = polyfit(x,y,3)
  fit_fn = poly1d(fit)
  ax.plot(KK['x'],KK['y'],'o',KK['x'], fit_fn(KK['x']),'k',linewidth=4)
  ax.set_xlabel('x')
  ax.set_ylabel('y')

图表显示每组Z的最佳拟合线。我想在线上打印最佳拟合线的方程式。请在此处建议我可以做什么enter image description here

2 个答案:

答案 0 :(得分:5)

所以你需要编写一些将poly参数数组转换为latex字符串的函数,这是一个例子:

import pylab as pl
import numpy as np

x = np.random.randn(100)
y = 1 + 2 * x + 3 * x * x + np.random.randn(100) * 2

poly = pl.polyfit(x, y, 2)

def poly2latex(poly, variable="x", width=2):
    t = ["{0:0.{width}f}"]
    t.append(t[-1] + " {variable}")
    t.append(t[-1] + "^{1}")

    def f():
        for i, v in enumerate(reversed(poly)):
            idx = i if i < 2 else 2
            yield t[idx].format(v, i, variable=variable, width=width)

    return "${}$".format("+".join(f()))

pl.plot(x, y, "o", alpha=0.4)
x2 = np.linspace(-2, 2, 100)
y2 = np.polyval(poly, x2)
pl.plot(x2, y2, lw=2, color="r")
pl.text(x2[5], y2[5], poly2latex(poly), fontsize=16)

这是输出:

enter image description here

答案 1 :(得分:0)

这是一个班轮。

如果public class GeneFinderYang { public static int findStopIndex(String dna, int index){ int stop1 = dna.indexOf("tga", index); if (stop1 == -1 || (stop1 - index) % 3 != 0) { stop1 = dna.length(); } int stop2 = dna.indexOf("taa", index); if (stop2 == -1 || (stop2 - index) % 3 != 0) { stop2 = dna.length(); } int stop3 = dna.indexOf("tag", index); if (stop3 == -1 || (stop3 - index) % 3 != 0) { stop3 = dna.length(); } return Math.min(stop1, Math.min(stop2,stop3)); } public static void printAll(String dna){ String dnaLow = dna.toLowerCase(); int start = 0; while (true) { int loc = dnaLow.indexOf( "atg", start ); int stop = findStopIndex( dnaLow, loc+3 ); if ( stop != dna.length() ) { System.out.println( dna.substring(loc, stop) ); start = stop + 3; } else { start = start + 3; } } } // demo public static void testFinder() { String dna1 = "ATGAAATGAAAA"; System.out.println("DNA string is: \n" +dna1); System.out.println("Genes found are:"); printAll(dna1); System.out.print("\n"); } public static void main(String[] args) { testFinder(); } } fit对象,则在绘制拟合线时,只需使用poly1d参数,如下所示

label