How To Switch Between Diagrams With A Button In 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
Solution 1:
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)
classIndex(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]
defplot(self, x):
self.current += 1if self.current%2:
self.values1()
else:
self.values2()
defvalues1(self):
l.set_xdata(self.x1)
l.set_ydata(self.y1)
plt.draw()
defvalues2(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()
Solution 2:
For those, who want to switch between bar- or plot diagrams (works for both types of diagram). I also think it is much cleaner to do it this way.
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
class Index(object):
def start(self, event=None):
ax.clear()
x_values = [1, 2, 3, 4, 5]
y_values = [3, 5, 2, 19, 1]
ax.bar(x_values, y_values)
plt.draw()
def next(self, event):
ax.clear()
x_values = [1, 2, 3, 4, 5]
y_values = [20, 15, 10, 5, 1]
ax.bar(x_values, y_values)
plt.draw()
def prev(self, event):
ax.clear()
x_values = [1, 2, 3, 4, 5]
y_values = [1, 5, 10, 15, 20]
ax.bar(x_values, y_values)
plt.draw()
ax = plt.gca()
callback = Index()
callback.start()
axprev = plt.axes([0.59, 0.002, 0.1, 0.075])
bprev = Button(axprev, 'Previous')
bprev.on_clicked(callback.prev)
axstart = plt.axes([0.7, 0.002, 0.1, 0.075])
bstart = Button(axstart, 'Start')
bstart.on_clicked(callback.start)
axnext = plt.axes([0.81, 0.002, 0.1, 0.075])
bnext = Button(axnext, 'Next')
bnext.on_clicked(callback.next)
plt.show()
Post a Comment for "How To Switch Between Diagrams With A Button In Matplotlib"