How to use the Span Selector on a embedded figure of matplotlib widget?

Julio Cuadros :

I am working on GUI where I have a system with graphs.

I want to use the spanselector in the graph i do visualize.

I have searched and i can't understand how to use the span selector while calling the matplotlib widget.

This is an example i'm following to plot. it has 3 parts(main,mplwidget,ui file)

the main code file

# ------------------------------------------------------
# ---------------------- main.py -----------------------
# ------------------------------------------------------
from PyQt5.QtWidgets import*
from PyQt5.uic import loadUi

from matplotlib.backends.backend_qt5agg import (NavigationToolbar2QT as NavigationToolbar)

import numpy as np
import random

#from matplotlib.widgets import SpanSelector

class MatplotlibWidget(QMainWindow):

    def __init__(self):

        QMainWindow.__init__(self)

        loadUi("qt_designer.ui",self)

        self.setWindowTitle("PyQt5 & Matplotlib Example GUI")

        self.pushButton_generate_random_signal.clicked.connect(self.update_graph)

        self.addToolBar(NavigationToolbar(self.MplWidget.canvas, self))


    def update_graph(self):

        fs = 500
        f = random.randint(1, 100)
        ts = 1/fs
        length_of_signal = 100
        t = np.linspace(0,1,length_of_signal)

        cosinus_signal = np.cos(2*np.pi*f*t)
        sinus_signal = np.sin(2*np.pi*f*t)

        self.MplWidget.canvas.axes.clear()
        self.MplWidget.canvas.axes.plot(t, cosinus_signal)
        self.MplWidget.canvas.axes.plot(t, sinus_signal)
        self.MplWidget.canvas.axes.legend(('cosinus', 'sinus'),loc='upper right')
        self.MplWidget.canvas.axes.set_title('Cosinus - Sinus Signal')
        self.MplWidget.canvas.draw()
        #span = self.MplWidget.canvas.axes.SpanSelector(ax1, onselect, 'horizontal', useblit=True,rectprops=dict(alpha=0.5, facecolor='red'))            


    def onselect(min_value, max_value):
        print(min_value, max_value)
        return min_value, max_value         



app = QApplication([])
window = MatplotlibWidget()
window.show()
app.exec_()

the mplwidget file

# ------------------------------------------------------
# -------------------- mplwidget.py --------------------
# ------------------------------------------------------
from PyQt5.QtWidgets import*

from matplotlib.backends.backend_qt5agg import FigureCanvas

from matplotlib.figure import Figure


class MplWidget(QWidget):

    def __init__(self, parent = None):

        QWidget.__init__(self, parent)

        self.canvas = FigureCanvas(Figure())

        vertical_layout = QVBoxLayout()
        vertical_layout.addWidget(self.canvas)

        self.canvas.axes = self.canvas.figure.add_subplot(111)
        self.setLayout(vertical_layout)

the ui file is attached to this link with all the codes: here

in the other way this is the example code to use the span selector:

import matplotlib.pyplot as plt
import matplotlib.widgets as mwidgets
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [10, 50, 100])
def onselect(vmin, vmax):
     print(vmin, vmax)
rectprops = dict(facecolor='blue', alpha=0.5)
span = mwidgets.SpanSelector(ax, onselect, 'horizontal',span_stays=True,button=1,,rectprops=rectprops)
fig.show()

//////////////////////////////////////////////////////////////////////////////

i tried a lot of ways to assess the span selector but im a little bit confused in the way it works and how i should connect the the structure of code?

if i run whithin The comented line: span = self.MplWidget.canvas.axes.SpanSelector(ax1, onselect, 'horizontal', useblit=True,rectprops=dict(alpha=0.5, facecolor='red'))

its shown the following error: AttributeError:'AxesSubplot' object has no attribute 'SpanSelector'

finally, this is the desire result

enter image description here

eyllanesc :

You have to pass the self.MplWidget.canvas.axes as ax:

    # ...
    self.MplWidget.canvas.draw()
    self.span = SpanSelector(
        self.MplWidget.canvas.axes,
        self.onselect,
        "horizontal",
        useblit=True,
        rectprops=dict(alpha=0.5, facecolor="red"),
    )

def onselect(self, min_value, max_value):
    print(min_value, max_value)

Note: since select is a method of the class, it must have self as the first parameter, and it must be invoked with self.select.

enter image description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=320030&siteId=1