使用 FigureCanvasTkAgg 嵌入 matplotlib 图表 - 设置 xticks

Embedding matplotlib chart using FigureCanvasTkAgg - set xticks

我正在创建一个包含各种嵌入式图表的 GUI。我正在使用 matplotlibFigureCanvasTkAggtkinter 来这样做,除了 x轴标签。在创建出现在新 window 中的 matplotlib 图表时,我可以使用 plt.xticks 轻松设置标签,但在使用 FigureCanvasTkAgg[=30 时则不能=].

我没有包括我的完整代码,因为它太长了,但我已经包括了我认为相关的所有代码(pyplot 在别处使用但不应该与我的问题相关)。这里的 chart.set_xticks 实际上并没有做任何事情:它没有在标题为 objects 的列表中显示标签,而是显示0 然后以整数形式上升,每个其他数据点实际上按照下图标记。我使用 chart.set_xticks 尝试了各种不同的方法,但只能使用 chart.set_xticks([]) 或使用 chart.set_xticks([0,1,2,3...]) 指定整数,它标记每个数据点但不使用我需要的标签。

有什么想法吗?

import matplotlib.pyplot as plt
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

objects = ["2x", "3x", "4x", "5x", "6x", "7x", "8x", "9x", "10x", "11x", "12x", "Year 2", "Year 3", "Year 4"]    
y_pos = np.arange(len(objects))

fig = Figure(figsize=(font * 8, font * 5))

chart = fig.add_subplot(111)
chart.set_ylim(ymin=0, ymax=32)
chart.bar(y_pos, plotList, color=colours, alpha=0.5, label="Table")
chart.bar(y_pos, inversePlotList, color=colours, label="Inverse")
chart.set_xticks(y_pos, objects)
chart.set_ylabel("Average score")
chart.legend()

canvas = FigureCanvasTkAgg(fig, master=userTablesFrame)
canvas.get_tk_widget().place(relx=0.5, rely=0.5, anchor=CENTER)
canvas.draw()

来自documentation of plt.xticks

Calling this function with arguments is the pyplot equivalent of calling set_xticks and set_xticklabels on the current axes.

因此,要获得相同的行为,您应该同时使用 set_xticksset_xticklabels

chart.set_xticks(y_pos)
chart.set_xticklabels(objects)