【问题标题】:Embedding matplotlib chart using FigureCanvasTkAgg - set xticks使用 FigureCanvasTkAgg 嵌入 matplotlib 图表 - 设置 xticks
【发布时间】:2018-10-23 12:00:25
【问题描述】:

我正在创建一个包含各种嵌入式图表的 GUI。我正在使用 ma​​tplotlibFigureCanvasTkAggtkinter 来执行此操作,除了 x 轴标签外一切正常。在创建出现在新窗口中的 matplotlib 图表时,我可以使用 plt.xticks 轻松设置标签,但在使用 FigureCanvasTkAgg 时却不行。

我没有包含我的完整代码,因为它太长了,但我包含了我认为相关的所有代码(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()

【问题讨论】:

    标签: python matplotlib tkinter tkinter-canvas


    【解决方案1】:

    来自documentation of plt.xticks

    用参数调用这个函数相当于在当前坐标轴上调用 set_xticks 和 set_xticklabels 的 pyplot。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-17
      • 1970-01-01
      • 2014-02-20
      • 1970-01-01
      • 2013-07-02
      • 2022-11-20
      • 2020-11-18
      • 2012-10-11
      相关资源
      最近更新 更多