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

How to Change Axis Tick Labels in dynamic tkinter chart using matplotlib

我在 matplotlib 中的 canvas 上有一个图表,它会经常更改,我无法更改轴标签,而只是在主要网格线上获得默认数字标签。这是一个简化的例子:

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()

此代码仅使用包含图形的 canvas 小部件启动 tkinter,然后在按下按钮时更新

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

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

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

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