如何在Matplotlib中使用按钮在图表之间切换 [英] How to switch between diagrams with a button in Matplotlib

查看:302
本文介绍了如何在Matplotlib中使用按钮在图表之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法,即可通过一个按钮在两个或多个图表之间进行切换?例如,我希望能够通过一个按钮在这两个图表之间切换,而不是一个一个地显示它们。

Is there an easy way, to switch between two or more diagrams with a button? I would like, for example be able to switch between these two diagrams with a button instead of showing them one after the other.

import matplotlib.pyplot as plt

x_values = [1, 2, 3, 4, 5]
y_values = [1, 4, 9, 16, 25]
plt.bar(x_values, y_values)
plt.show()

x_values = [5, 4, 3, 2, 1]
y_values = [1, 4, 9, 16, 25]
plt.bar(x_values, y_values)
plt.show()

我知道有一些解决此问题的示例,但是我根本无法解决它……

I know there are examples for this problem out there, but I simply can't get it to work...

这里是链接,它们显示了怎么做,但我不知道该怎么做...

Here is the link, where they show how to do it, but I don't understand how to do it...

链接: https://matplotlib.org/gallery/widgets/buttons.html

推荐答案

在这里,我从您提供的链接中修改了代码,以便根据当前使用的值使用不同的值集

Here I modified code from the link you supplied so that it uses different sets of values depending on what values are currently plotted.

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

x1_values = [1, 2, 3, 4, 5]
y1_values = [1, 4, 9, 16, 25]
l, = plt.plot(x1_values, y1_values)


class Index(object):
    def __init__(self):
        self.current = 1

        self.x1 = [5, 4, 3, 2, 1]
        self.y1 = [1, 4, 9, 16, 25]

        self.x2 = [1, 2, 3, 4, 5]
        self.y2 = [1, 4, 9, 16, 25]

    def plot(self, x):
        self.current += 1

        if self.current%2:
            self.values1()
        else:
            self.values2()

    def values1(self):
        l.set_xdata(self.x1)
        l.set_ydata(self.y1)
        plt.draw()

    def values2(self):
        l.set_xdata(self.x2)
        l.set_ydata(self.y2)
        plt.draw()

callback = Index()
axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bprev = Button(axnext, 'Switch')
bprev.on_clicked(callback.plot)

plt.show()

这篇关于如何在Matplotlib中使用按钮在图表之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆