python - 在现有主窗口上显示有关在 PyQt GUI 上选择组合框选项的图表
问题描述
所以我试图基本上设置某种工具,它允许我从数据框中选择一列,当我从组合框中选择该列时,显示该列分布的图表应该显示在同一个窗口中。我不知道该怎么办...
这就是我的组合框的外观:
我需要能够在同一窗口中显示图表(分布)。
我该怎么做?
解决方案
下面是一个示例,说明如何使用组合框在同一窗口中的数据框中绘制列中的数据。
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()
推荐阅读
- javascript - mongoose find() 方法不是服务调用中的函数错误
- list - 在 Flutter 中调用函数时遇到空引用问题
- mysql - MYSQL 将毫秒转换为仅 MM:SS
- c# - 手动调整位图大小
- python - 无法加载 CSS Django IIS
- java - java.lang.NoClassDefFoundError:Tomcat 10 中的 jakarta/servlet/jsp/jstl/core/LoopTag
- docker - 为什么 vscode 的远程资源管理器会得到旧容器的列表?(码头工人)
- php - 为什么 Laravel `middleware('auth:sanctum')` 会导致 302 问题?
- docker - Azure Fileshare - 使用 Docker-Compose 将不同的子文件夹/文件挂载到 ACI 上的卷
- python - 如何获取所有值直到某个定义的值以更改 Python Pandas 数据框中的列名称?