如何制作交互式matplotlib图例,以便可以从绘图中删除线条?

时间:2018-12-06 12:08:01

标签: python matplotlib plot tkinter

理想情况下,此实现是在图例标签旁边使用十字来实现的,可以单击该标签以将其从图中删除。现在,我试图通过单击图例条目的行以从绘图中删除图形来做到这一点。我是通过字典将图例条目映射到情节上的行的方式来实现的。我遇到的问题是,只要将多条线添加到绘图中,我就可以删除除第一条绘图以外的所有线。我怀疑这个问题可能是由于我重新创建了图例,可能与字典映射搞混了。

像这样在类init方法中初始化图

f = Figure(figsize=(1, 1), dpi=100)
self.chart = f.add_subplot(111)
self.lined = dict()
self.canvas = FigureCanvasTkAgg(f, self)
self.canvas.draw()
self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
self.canvas.mpl_connect('pick_event', self.remove_graph)

这些是与绘制线条并将其删除有关的功能。

def plot_prices(self, event=None):
    ticker = self.entry.get().upper()
    with open(suffixed_ticker_dump_path, 'rb') as tickers:
        tickers = pickle.load(tickers)
        if ticker not in tickers:
            self.popupmsg("Invalid ticker input. Enter a valid ticker.")
        else:
            df = pd.read_csv(os.path.join(daily_data_dir, '{}.csv'.format(ticker)),
                             index_col=0, parse_dates=True)
            prices = df['adjusted_close'].replace(0, np.nan)
            line,=self.chart.plot(prices.interpolate(), label=ticker)

            self.leg = self.chart.legend(loc='lower right')
            legline = self.leg.get_lines()[-1]
            legline.set_picker(5)
            self.lined[legline] = line

            self.canvas.draw()

def remove_graph(self, event=None):
    legline = event.artist
    origline = self.lined[legline]
    origline.remove()
    self.leg = self.chart.legend(loc='lower right')
    self.canvas.draw()

1 个答案:

答案 0 :(得分:-1)

最终通过简单地清除或重设字典映射图例条目到图表上的线条(绘制了一条线或删除了一条线)而解决了该问题。我想它由于某些技术性而无法使用,因为图例和图表中对线条的引用有所不同,除非有人有更好的解决方案,否则我将使用它,因为它不需要太多代码。

def plot_prices(self, event=None):
    ticker = self.entry.get().upper()
    with open(suffixed_ticker_dump_path, 'rb') as tickers:
        tickers = pickle.load(tickers)
        if ticker not in tickers:
            self.popupmsg("Invalid ticker input. Enter a valid ticker.")
        else:
            df = pd.read_csv(os.path.join(daily_data_dir, '{}.csv'.format(ticker)),
                             index_col=0, parse_dates=True)
            prices = df['adjusted_close'].replace(0, np.nan)
            line,=self.chart.plot(prices.interpolate(), label=ticker)
            self.leg = self.chart.legend(loc='lower right')
            self.reset_line_dict()
            self.canvas.draw()

def remove_graph(self, event=None):
    legline = event.artist
    origline = self.lined[legline]
    self.chart.lines.remove(origline)
    self.leg = self.chart.legend(loc='lower right')
    self.reset_line_dict()
    self.canvas.draw()

def reset_line_dict(self):
    self.lined.clear()
    for legline, origline in zip(self.leg.get_lines(), self.chart.get_lines()):
        legline.set_picker(5)  # 5 pts tolerance
        self.lined[legline] = origline