更新pyplot maker在tkinter按钮上的位置点击

时间:2017-12-16 13:58:05

标签: python matplotlib plot tkinter

我正在努力找出一种绘制图形的方法,其中x轴和y轴的值来自两个tkinter spinbox,其中x轴的spinbox范围是125到8000,y轴是-10到125 ,根据旋转框提供的值按下tkinter按钮时,它会从图形中的一个点绘制到另一个点。

示例代码为:

from tkinter import *

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import numpy as np
import collections

class PlotClass():
    def __init__(self):
         fig = Figure(figsize=(5,5),dpi=70,facecolor='cyan')
         ax = fig.subplots()
         ax.set_xlim(100,9000)
         ax.set_ylim(130,-10)

         x = [125,250,500,1000,2000,4000,8000]
         ticks = [125,250,500,"1K","2K","4K","8K"]
         xm = [750,1500,3000,6000]

         ax.set_xscale('log', basex=2)
         ax.set_xticks(x)
         ax.set_xticks(xm, minor=True)
         ax.set_xticklabels(ticks)
         ax.set_xticklabels([""]*len(xm), minor=True)

         ax.yaxis.set_ticks([120,110,100,90,80,70,60,50,40,30,20,10,0,-10])

         self.line2,= ax.plot([],[],'-o',markersize=15.0,mew=2)
         ax.grid(color="grey")
         ax.grid(axis="x", which='minor',color="grey", linestyle="--")
         self.canvas = canvas = FigureCanvasTkAgg(fig, master=master)
         canvas.show()
         canvas.get_tk_widget().grid(column=0,row=2,columnspan=3,rowspan=15)
         self.spin = Spinbox(master, from_=125,to=8000,command=self.action)
         self.spin.grid(column=5,row=2)

         self.spin2 = Spinbox(master, from_=-10,to=125,command=self.action)
         self.spin2.grid(column=5,row=3)

         self.button = Button(master, text="plot here",command=self.plot)
         self.button.grid(column=5,row=4)

    def linecreate(self, x=1000,y=20):
        X,Y = self.line2.get_data()
        if x in X:
            ch = list(X)
            counti = ch.count(x)
            Y[counti] = y
            print("Working")
            print(Y)
            self.canvas.draw_idle()
        else:
            X = np.append(X,[x])
            Y = np.append(Y,[y])
            self.line2.set_data(X,Y)
            self.canvas.draw_idle()


    def plot(self):
        self.linecreate(float(self.spin.get()),float(self.spin2.get()))

master = Tk()
plotter = PlotClass()
plotter.ok(125,10)
master.mainloop()

现在的问题是,它需要检查一个特定的标记是否已经在同一个x轴上,它通常会将一个新行绘制到添加新值的位置,但是我需要一种方法,这样当x轴是125并且它已经被绘制一次到y轴上的任何值,如50,然后它在x中绘制500,在y中绘制90,最后它再次尝试在x中绘制125和在y中绘制20,图形会创建一个标记,但我需要使用新的Y值重新绘制旧图,而不创建新标记。

在上面的代码中,我尝试If x in X:检查是否已经绘制了x轴,即使我可以检查但是我不能用新值替换Y轴值并重新绘制它。

1 个答案:

答案 0 :(得分:0)

如果值已存在,您忘记使用self.line2.set_data(X,Y)更新地图。

def linecreate(self, x=1000,y=20):
    X,Y = self.line2.get_data()
    if x in X:
        ch = list(X)
        counti = ch.index(x)
        Y[counti] = y           
    else:
        X = np.append(X,[x])
        Y = np.append(Y,[y])
    self.line2.set_data(X,Y)
    self.canvas.draw_idle()
相关问题