python-3.x 每次单击按钮时,matplotlib图都会被覆盖

9nvpjoqh  于 2023-02-26  发布在  Python
关注(0)|答案(1)|浏览(185)

下面的代码在每次单击按钮时绘制图形。我希望图形得到更新而不是覆盖

def plot_cr():
        section_length = 220
        section_width = 220
        angle = np.linspace(np.pi, 3 * np.pi / 2, 150)
        side_view_width = float(section_width) / 100
        outer_radius = float(12) + side_view_width
        x = float(12) * np.cos(angle)
        y = float(12) * np.sin(angle)
        fig1 = Figure(figsize=(10, 10), dpi=60)
        axes = fig1.add_subplot(111)
        axes.clear()
        axes.plot(x, y, color="green")
        axes.set_aspect(1)
        axes.set_title('Caster Diagram')
        canvas_side = FigureCanvasTkAgg(fig1, master=caster_graph)
        canvas_side.draw()
        canvas_side.get_tk_widget().pack(side="left", fill="both", expand=True)
        axes.get_xaxis().set_visible(False)
        axes.get_yaxis().set_visible(False)
        plt.rcParams['axes.formatter.useoffset'] = False
        fig1.tight_layout()
    plot_button = Button(master=cnozzle, command=plot_cr, height=1, width=20, text="Get Cooling Profile")
    plot_button.grid(row=2, column=0, padx=25, columnspan=2, pady=5)

我试过axes.clear()命令,但它不起作用。请建议如何修复。

ffvjumwh

ffvjumwh1#

根据您的注解,一个选项是将函数放入一个类中,该类记录绘图是否已创建,并具有一个类方法,仅在绘图不存在时绘制该绘图。例如:

class Plotter:
    def __init__(self):
        self._plot_exists = False  # no plot

    def plot_cr(self):
        if not self._plot_exists:
            # create plot if no plot exists
            section_length = 220
            section_width = 220
            angle = np.linspace(np.pi, 3 * np.pi / 2, 150)
            side_view_width = float(section_width) / 100
            outer_radius = float(12) + side_view_width
            x = float(12) * np.cos(angle)
            y = float(12) * np.sin(angle)
            fig1 = Figure(figsize=(10, 10), dpi=60)
            axes = fig1.add_subplot(111)
            axes.clear()
            axes.plot(x, y, color="green")
            axes.set_aspect(1)
            axes.set_title('Caster Diagram')
            canvas_side = FigureCanvasTkAgg(fig1, master=caster_graph)
            canvas_side.draw()
            canvas_side.get_tk_widget().pack(side="left", fill="both", expand=True)
            axes.get_xaxis().set_visible(False)
            axes.get_yaxis().set_visible(False)
            plt.rcParams['axes.formatter.useoffset'] = False
            fig1.tight_layout()

            # set _plot_exists to True
            self._plot_exists = True

plotter = Plotter()  # create instance of class
plot_button = Button(
    master=cnozzle,
    command=plotter.plot_cr,  # pass the class function
    height=1,
    width=20,
    text="Get Cooling Profile"
)
plot_button.grid(row=2, column=0, padx=25, columnspan=2, pady=5)

相关问题