2013-08-24 28 views
2

我的python程序能够绘制图形,但它的曲线是不现实的。如何绘制逼真的曲线使用Scipy

例如:enter image description here

我怎样才能顺利恩图使用SciPy的?我已经看过以前的关于这个问题的教程,但他们倾向于使用numpy和它的arange()功能。由于我的程序没有派生出从numpy绘制点,我认为它的功能在这种情况下是无用的。

import Tkinter as Tk 
import ttk 
import sympy 
import matplotlib.pyplot as plt 

x = sympy.symbols('x') 

class Interface(ttk.Frame): 
    def __init__(self,parent=None): 
     ttk.Frame.__init__(self,parent) 
     self.parent = parent 
     self.InitUI() 

    def InitUI(self): 
     self.x_from_1 = ttk.Label(self.parent, text= ' X values should be from : ') 
     self.x_from_2 = ttk.Label(self.parent, text = ' To : ') 
     self.x_from_1_inp = ttk.Entry(self.parent) 
     self.x_from_2_inp = ttk.Entry(self.parent) 

     self.equation_label = ttk.Label(self.parent,text = 'Equation : ') 
     self.equation = ttk.Entry(self.parent) 

     self.submit = ttk.Button(self.parent,text='Plot',command= self.Plot) 

# Grid Allocations Here 
     self.x_from_1.grid(column=0,row=0) 
     self.x_from_2.grid(column=5,row=0) 
     self.x_from_1_inp.grid(column=1,row=0) 
     self.x_from_2_inp.grid(column=10,row=0) 

     self.equation_label.grid(column = 0,row=3) 
     self.equation.grid(column=1,row=3,ipadx= 35) 

     self.submit.grid(column=10,row=5) 
# Grid Allocations End Here 


    def Plot(self): 
     x_vals = range(int(self.x_from_1_inp.get()),int(self.x_from_2_inp.get())) 
     eq = eval(self.equation.get()) 
     self.prepare_table(x_vals,eq) 
     plt.plot(x_vals,self.y_values) 
     plt.grid(True) 
     plt.show() 

    def prepare_table(self,x_values,equation): 
     y = [] 
     for i in x_values: 
      y.append(equation.subs(x,i)) 
     self.y_values = y 
     return self.y_values 

root = Tk.Tk() 
root.title('Graphs') 
app = Interface(root) 
app.mainloop() 
+0

你可以适应二次此类数据'numpy.polyfit',然后绘制这一点。或者,查看BioPython中的LO(W)ESS实现。 –

回答

4

使用scipy.interpolate.interp1dscipy.interpolate.interp1d

... 
from scipy.interpolate import interp1d 
import numpy 

class Interface(ttk.Frame): 
    .... 
    def Plot(self): 
     x_vals = range(int(self.x_from_1_inp.get()),int(self.x_from_2_inp.get())) 
     eq = eval(self.equation.get()) 
     self.prepare_table(x_vals,eq) 
     f = interp1d(x_vals, self.y_values, kind='cubic') 
     x_new = numpy.linspace(x_vals[0], x_vals[-1], (x_vals[-1]-x_vals[0])*4) 
     plt.plot(x_new, f(x_new)) 
     plt.grid(True) 
     plt.show() 
+0

绘制曲线的精度取决于什么?这行是做什么的?x_new = numpy.linspace(x_vals [0],x_vals [-1],(x_vals [-1] -x_vals [0])* 4)' –

+0

@KDawG,对不起,我没有了解曲线的准确性。它可能取决于'x_new'和'kind'('linear','nearest','zero','slinear','quadratic','cubic')之一的大小。 – falsetru

+1

@KDawG'numpy.linspace(x,y,n)'在'x'和'y'('x','y'包括)之间产生'n'数字。例如'numpy.linspace(0,2,10)'产生'[0,0.5,1,1.5,2]'。 – falsetru