简体   繁体   中英

Display a graph on selecting a combobox option on PyQt GUI , over an existing mainwindow

So I am trying to basically set up some kind of a tool which allows me to select a column from a dataframe and when I select that column from the combobox, a graph showing the distribution of that column should be displayed in the same Window. I don't know how to go about this...

This is how my combobox looks :

在此处输入图片说明

I need to be able show a graph (distribution ) in the same window.

How do I go about this ?

Here is an example to illustrate how to use a combo box to plot the data in a column in a data frame in the same window.

from PyQt5 import QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
import pandas as pd
import os

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.combo = QtWidgets.QComboBox()
        self.combo.addItem("Choose a field")
        self.button = QtWidgets.QPushButton('Read csv file')

        # axes and widget for plotting and displaying the figure
        self.fig, self.ax = plt.subplots()
        self.figure_widget = FigureCanvas(self.fig)
        plt.tight_layout()

        # set up layout
        vlayout = QtWidgets.QVBoxLayout(self)
        hlayout = QtWidgets.QHBoxLayout()
        hlayout.addWidget(self.combo)
        hlayout.addWidget(self.button)
        hlayout.addStretch(2)
        vlayout.addLayout(hlayout)
        vlayout.addWidget(self.figure_widget)

        self.button.clicked.connect(self.read_data)
        self.combo.currentTextChanged.connect(self.field_changed)

    def read_data(self):
        dialog = QtWidgets.QFileDialog(self, directory=os.curdir, caption='Open data file' )
        dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen)
        dialog.setFileMode(QtWidgets.QFileDialog.ExistingFile)
        if dialog.exec():
            # read data and add columns to combo box
            file = dialog.selectedFiles()[0]
            self.data = pd.read_csv(file)
            self.combo.clear()
            self.combo.addItem("Choose a field")
            for field in self.data.columns:
                self.combo.addItem(field)
            self.combo.setCurrentIndex(0)

    def field_changed(self, field):
        self.ax.clear()
        if field in self.data.columns:
            self.data.plot(y=field, ax=self.ax)
            self.ax.set_ylabel(field)
            self.ax.set_xlabel('index')
        plt.tight_layout()
        self.fig.canvas.draw()


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    widget = Widget()
    widget.show()
    app.exec()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM