首页 > 解决方案 > 使用 Matplotlib (Python) 绘图内的绘图和按钮

问题描述

我正在尝试自学如何集成plotsbuttons并且通过该扩展,实际使用Classes.

我给自己设定的挑战是:

  1. 创建散点图(完成)
  2. 创建一个在现有散点图中生成新散点图的按钮(完成)
  3. 在新散点图中创建一个按钮(完成)
  4. 为新按钮分配关闭新散点图的功能(卡在这里)

这是我到目前为止的进展:

在此处输入图像描述

我的代码如下:

欢迎任何提示!


import matplotlib.pyplot as plt
from matplotlib.widgets import Button


  # Junk data for the purpose of my question

x = [1, 1, 1, 2, 2, 2, 3, 3, 3]
y = [1, 2, 3, 1, 2, 3, 1, 2, 3]

fig, (ax1) = plt.subplots()

ax1.scatter(x, y)  # plot (x, y) data as a scatter plot

class Initial_plot(object):

    def close_plot(self, event):
        plt.close()

    def add_axis(self, event):
        plt.axes([0.3, 0.2, 0.5, 0.51])

        x = [1, 1, 1, 2, 2, 2, 3, 3, 3]
        y = [1, 2, 3, 1, 2, 3, 1, 2, 3]

        plt.scatter(x, y)

        class Second_plot(object):

            def close_addplot(self, event):
                plt.close()


          # Button to close the new scatter plot
        axclose_addplot = plt.axes([0.4, 0.4, 0.15, 0.1])
        bclose_addplot = Button(axclose_addplot, 'Close add plot')
        bclose_addplot.on_clicked(callback.close_addplot)


callback = Initial_plot()


  # Add button for a new scatter plot

axadd_plot = plt.axes([0.5, 0.01, 0.1, 0.071])
badd_plot = Button(axadd_plot, 'Add Plot')
badd_plot.on_clicked(callback.add_axis)



  # Exit Button for inital scatter plot
axclose_plot = plt.axes([0.7, 0.01, 0.1, 0.071])  # co-ords of button
bclose_plot = Button(axclose_plot, 'Close')  # name of button
bclose_plot.on_clicked(callback.close_plot)  # enables event upon clicking the button

plt.show()  #display the plot

标签: pythonclassmatplotlibbutton

解决方案


推荐阅读