Home > Enterprise >  How to create a button-based GUI in Python that displays a new plot every time clicked
How to create a button-based GUI in Python that displays a new plot every time clicked

Time:10-10

For each “CODE” i need to display a plot that has the four “vPoint” on the vertical axis and the four “step” on the horizontal one. So i need to create a viewer/GUI that allows the user to switch between the plots of each row. enter image description here

I've created a for loop:

for ind in dataOK.index:
   r1=dataOK['vPoint1_R4'][ind]
   r2=dataOK['vPoint2_R4'][ind]
   r3=dataOK['vPoint3_R4'][ind]
   r4=dataOK['vPoint4_R4'][ind]
   t_step=[15,30,45,60]
   vpoints=[r1,r2,r3,r4]

   plt.scatter(t_step,vpoints)
   plt.plot(t_step, vpoints)
   plt.title(ind)
plt.show()

But using plt.show() out of the loop it creates a unique plot with all the graphs merged (figure below). Is there a way to implement a button-based GUI in python that uses this for loop to display the next plot every time I click?enter image description here

CodePudding user response:

Matplotlib itself provides already a great Button Example. Based on it, you are probably looking for something like:

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

def getData(ind):
    return dataOK['index'][ind], dataOK['vPoint1_R4'][ind], dataOK['vPoint2_R4'][ind], dataOK['vPoint3_R4'][ind], dataOK['vPoint4_R4'][ind]

dataOK = {
    'index': list(range(0,12)),
    'vPoint1_R4': random.sample(range(0, 600), 12),
    'vPoint2_R4': random.sample(range(0, 600), 12),
    'vPoint3_R4': random.sample(range(0, 600), 12),
    'vPoint4_R4': random.sample(range(0, 600), 12),
}

fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2) #leave space for buttons
ax.set_ylim([0, 600])

ind, r1, r2, r3, r4 = getData(0) 
t_step = [15, 30, 45, 60]
vpoints = [r1, r2, r3, r4]

l, = plt.plot(t_step, vpoints, '-o')
pltTitle = plt.title(ind)

class Index:
    selectedIndex = 0

    def updatePlot(self):
        i = self.selectedIndex % len(dataOK['index'])
        currentIndex = dataOK['index'][i]

        ind, r1, r2, r3, r4 = getData(currentIndex)
        l.set_ydata([r1, r2, r3, r4])
        pltTitle.set_text(ind)
        plt.draw()

    def next(self, event):
        self.selectedIndex  = 1
        self.updatePlot()

    def prev(self, event):
        self.selectedIndex -= 1
        self.updatePlot()

callback = Index()
axprev = fig.add_axes([0.7, 0.05, 0.1, 0.075])
axnext = fig.add_axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'Next')
bnext.on_clicked(callback.next)
bprev = Button(axprev, 'Previous')
bprev.on_clicked(callback.prev)

plt.show()
  • Related