如何使用Scipy绘制逼真的曲线

时间:2013-08-24 12:17:57

标签: python python-2.7 scipy

我的python程序能够绘制图形,但它的曲线是不现实的。

例如: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()

1 个答案:

答案 0 :(得分: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()