如何使用 matplotlib 更改动态 tkinter 图表中的轴刻度标签



我在 matplotlib 的画布上有一个图表,该图表将相当频繁地更改,并且我无法更改轴标签,而是在主要网格线上获取默认数字标签。下面是一个简化的示例:

import matplotlib.pyplot as plt
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
#import matplotlib.animation as animation
#from matplotlib import style
import numpy as np
import Tkinter as tk
import ttk
def customplot(f):
    try:
        f.clf()
        #plt.clf()
        #ax.clear()
        #f.delaxes(ax)
    except:
        None
    try:
        ax=ax
    except:
        ax=f.add_subplot(111)
    ax.scatter(np.random.uniform(size=3),np.random.uniform(size=3))
    plt.xticks([1,2,3],['one','two','three']) #THIS LINE!!!!???
class My_GUI:
    def __init__(self,master):
        self.master=master
        self.f = Figure(figsize=(5,5), dpi=100)
        self.canvas1=FigureCanvasTkAgg(self.f,self.master)
        self.updatechartbutton=tk.Button(master=master,text='update plot',command=self.drawcustomplot)
        self.canvas1.get_tk_widget().pack(side="top",fill='x',expand=True)
        #self.canvas1.mpl_connect('pick_event',self.onpick)
        self.toolbar=NavigationToolbar2TkAgg(self.canvas1,master)
        self.toolbar.update()
        self.toolbar.pack(side='top',fill='x')
        self.updatechartbutton.pack(side='top')
    def drawcustomplot(self):
        customplot(self.f)
        plt.xticks([1,2,3],['one','two','three'])
        self.canvas1.show()
root=tk.Tk()
gui=My_GUI(root)
root.mainloop()

此代码只是启动一个带有包含图形的画布小部件的 tkinter,然后在按下按钮时更新该图形

您会注意到我尝试设置plt.xticks customplot函数无济于事。我意识到这可能与使用 pyplot 声明它们未正确转换为 tkinter 的更改有关,但我不确定如何正确执行此操作。提前感谢任何帮助!

不使用plt,您必须使用 ax(AxesSubPlot 对象(,在您的情况下它会更改:

plt.xticks([1,2,3],['one','two','three']) 

ax.set_xticks([1,2,3])
ax.set_xticklabels(['one','two','three'])

最新更新