首页 > 解决方案 > Matplotlib 按钮画线

问题描述

我想创建一些可以显示(并用同一个按钮隐藏)一条线的东西。

这是我目前所拥有的:

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


fig, ax = plt.subplots()

class Index(object):
   ind = 0

   def test(self, event):
     self.plt.plot([0, 0], [1, 1])
     plt.draw()


callback = Index()
axtest = plt.axes([0.81, 0.05, 0.1, 0.075])
btest = Button(axtest, 'Test')
btest.on_clicked(callback.test)


plt.show()

有人可以帮我写这个脚本吗?我真的不知道该怎么做。

标签: python-2.7matplotlibmatplotlib-widget

解决方案


self.plt没有意义。此外,您的 scipt 将始终添加新情节。相反,您可能想要切换现有绘图的可见性(并可能更改数据)。

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


fig, ax = plt.subplots()

class Index(object):
    def __init__(self, line):
        self.line = line

    def test(self, event):
        if self.line.get_visible():
            self.line.set_visible(False)
        else:
            # possibly change data here, for now same data is used
            self.line.set_data([0,1],[0,1])
            self.line.set_visible(True)
            self.line.axes.relim()
            self.line.axes.autoscale_view()
        self.line.figure.canvas.draw()

line, = plt.plot([],[], visible=False)

callback = Index(line)
axtest = plt.axes([0.81, 0.05, 0.1, 0.075])
btest = Button(axtest, 'Test')
btest.on_clicked(callback.test)


plt.show()

推荐阅读