2

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

例如 :在此处输入图像描述

如何使用 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()
4

1 回答 1

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()
于 2013-08-24T13:09:01.347 回答