【问题标题】:Need help plotting graphs in tkinter using matplotlib [duplicate]需要帮助使用matplotlib在tkinter中绘制图形[重复]
【发布时间】:2019-01-16 20:02:29
【问题描述】:

我正在编写一个程序,使用 matplotlibtkinter 通过 GUI 绘制图形。一切都按计划进行,除了在我输入 xy 变量之后,绘制的图形是精确的 x=y 线,除了轴上的数字按输入顺序排列。

代码如下:

我已经尝试过使用来自matplotlibaxis 命令,但没有成功。

x=[]
y=[]

enterx = ttk.Entry(self)
enterx.pack()
enterx.insert(0,"X")
entery = ttk.Entry(self)
entery.pack()
entery.insert(0,"Y")

def creategraph(self,parent,x,y,enterx,entery):
    f = Figure(figsize=(5,5), dpi=100)
    a = f.add_subplot(111)
    textx = enterx.get()
    texty = entery.get()
    x=textx.split(",")
    y=texty.split(",")
    a.plot(x,y)

    canvas = FigureCanvasTkAgg(f,self)
    canvas.draw()
    toolbar = NavigationToolbar2Tk(canvas,self)
    toolbar.update()
    canvas._tkcanvas.pack(side=tk.TOP,fill=tk.BOTH, expand=True)
    canvas.get_tk_widget().pack(side=tk.BOTTOM,fill=tk.BOTH, expand=True)

代码不包括tkinter 窗口初始化或小部件。我以为它会在轴上绘制一条具有均匀间隔数字的线,但事实并非如此。

【问题讨论】:

    标签: python python-3.x matplotlib tkinter


    【解决方案1】:

    问题似乎是您正在绘制的值是字符串,因此顺序不是基于数字。以下是一种解决方案:使用map 将您的字符串值转换为int(整数)类型。修改后的代码行用注释标记。


    def creategraph(self,parent,x,y,enterx,entery):
        f = Figure(figsize=(5,5), dpi=100)
        a = f.add_subplot(111)
        textx = enterx.get()
        texty = entery.get()
        x=list(map(int, textx.split(","))) # <---- Convert strings to int 
        y=list(map(int, texty.split(","))) # <---- Convert strings to int 
        a.plot(x,y)
    

    【讨论】:

    • 非常感谢!这实际上真的帮助了我的项目,没想到我什至会得到回应。我只是觉得我没有转换成整数有点愚蠢。
    • 不客气
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 2011-12-13
    • 1970-01-01
    • 2021-10-06
    • 2013-09-15
    • 2020-12-12
    相关资源
    最近更新 更多