【问题标题】:Matplotlib grid styles and titles not showingMatplotlib 网格样式和标题未显示
【发布时间】:2020-11-11 23:15:42
【问题描述】:

经过大量奔波试图让 matplotlib 图显示在特定的 Tkinter 框架中,但网格样式和标题没有显示。绘图创建与一个功能相关联,该功能与一个工作正常的按钮相关联。当绘图单独绘制图表或调用 plt.show() 时,该样式有效。当整个事物与一个类相关联并以这种方式创建时,它也可以工作。

有人知道为什么这不起作用吗?

def create_all_graph():
    recruiter = submit_entry.get()

    # Gather data for marketing calls
    rec_filter = df_tgr_year["recruiter"] == recruiter
    x_week = df_tgr_year.loc[rec_filter, ["week"]]

    # Marketing Calls
    mc_y_metric = df_tgr_year.loc[rec_filter, ["marketing_calls"]]

    # plot graph
    mc_figure = Figure(figsize=(4, 3), dpi=100)
    mc_plot = mc_figure.add_subplot(111)
    mc_plot.plot(x_week, mc_y_metric, color="#159cff", linewidth=2, marker='h', markerfacecolor="#FFFFFF",
                 markeredgewidth=2, markersize=5)

    mc_canvas = FigureCanvasTkAgg(mc_figure, master=graph_frame)
    mc_canvas.draw()
    mc_canvas.get_tk_widget().grid(row=1, column=0)

    plt.ylim(ymin=0)
    plt.xlim(xmin=0)

    plt.title("Marketing Calls")
    plt.xlabel("Week")
    plt.ylabel("Marketing Calls")

    plt.minorticks_on()
    plt.grid(which="major", linestyle="-", linewidth="0.5", color="#d7eeff")
    plt.grid(which="minor", linestyle="-", linewidth="0.5", color="#d7eeff")

    plt.tight_layout()

触发这个问题的代码块也有一些有趣的地方,但让我们再等一下。

【问题讨论】:

    标签: python matplotlib tkinter tkinter-canvas


    【解决方案1】:

    来自matplotlib docs

    Matplotlib 有两个接口。第一个是面向对象(OO)的接口。在这种情况下,我们使用axes.Axes 的实例来在figure.Figure 的实例上呈现可视化。

    第二个是基于 MATLAB 并使用基于状态的接口。这被封装在 pyplot 模块中。请参阅 pyplot 教程以更深入地了解 pyplot 界面。

    您的图表没有显示标签和其他样式,因为您使用面向对象的界面进行绘图并使用基于状态的界面设置样式。将所有内容切换到面向对象的界面。

    在这里,我已将您的标签切换到面向对象的界面,并将您的代码与a tutorial 组合成minimal reproducible example

    import tkinter
    
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    from matplotlib.figure import Figure
    from matplotlib.axes import Axes
    
    
    graph_frame = tkinter.Tk()
    graph_frame.wm_title("Embedding in Tk")
    
    x_week = [1, 2, 3]
    mc_y_metric = [10, 20, 15]
    
    # plot graph
    mc_figure = Figure(figsize=(4, 3), dpi=100)
    mc_plot: Axes = mc_figure.add_subplot(111)
    mc_plot.plot(x_week, mc_y_metric, color="#159cff", linewidth=2, marker='h', markerfacecolor="#FFFFFF",
                 markeredgewidth=2, markersize=5)
    
    mc_plot.set_title("Marketing Calls")
    mc_plot.set_xlabel("Week")
    mc_plot.set_ylabel("Marketing Calls")
    
    mc_figure.tight_layout()
    
    mc_canvas = FigureCanvasTkAgg(mc_figure, master=graph_frame)
    mc_canvas.draw()
    mc_canvas.get_tk_widget().grid(row=1, column=0)
    
    tkinter.mainloop()
    

    【讨论】:

    • 感谢您的帮助解释和示例!这很奏效,虽然我看到问题源于我不了解不同的模块对象如何协同工作,但我必须自己研究才能到达任何地方
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 2013-03-18
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多