如何将轴标签和标题添加到集成到tkinter窗口中的matplotlib



我已经搜索了文档,但我不知道如何标记绘图的轴和标题。

这是我当前的代码:

font = {'size'   : 40}
plot.rc('font', **font)
fig = Figure(figsize=(32, 31), dpi=20)
plot.figure(facecolor='yellow')
canvas = FigureCanvasTkAgg(fig, master=graphFrame)  # A tk.DrawingArea.
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
toolbar = NavigationToolbar2Tk(canvas, graphFrame)
toolbar.update()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def plotgraph(x, y):
fig.clear()
fig.add_subplot(111).plot(x, y, linewidth=9.0)
canvas.draw_idle()

axis = fig.add_subplot(111)
testx = np.ndarray.tolist(np.arange(1,41))
testy = np.ndarray.tolist(np.random.randint(40, size=40))
def updateCurrentGraph(gx, gy, ylabel, xlabel, title):
plotgraph(gx, gy)

axis.set_ylabel(ylabel)
axis.set_xlabel(xlabel)
axis.set_title(title)

testx.pop(0)
testx.append(int(testx[-1] + 1))

testy.pop(0)
testy.append(int(randint(1, 40)))

root.after(500, updateCurrentGraph, gx, gy, ylabel, xlabel, title)
updateCurrentGraph(testx, testy, "Loss", "Time", "Loss over time")
root.mainloop()

我试着放

axis = fig.add_subplot(111)

作为变量声明插入到plotgraph函数中,但这只是引发了一个未声明轴的错误(即使我运行plotgrap函数来声明它(。按照上面显示的方式运行程序效果很好,只是标签根本没有显示。

您需要使用plot.titleaxis.set_xlabelaxis.set_ylabel

最新更新