import sys
import csv
from PyQt5.QtWidgets import *
from PyQt5 import uic
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvas as FigureCanvas
from matplotlib.figure import Figure
form_class = uic.loadUiType('./pyQt/ui/miniproject1.ui')[0]
class Class(QWidget, form_class):
second_ui_instance = None
def __init__(self):
super().__init__()
f = open('./pyQt/csv/mpg.csv', encoding='cp949')
self.data = list(csv.reader(f))
f.close()
self.data.pop(0)
self.setupUi(self)
self.initUI()
self.button.clicked.connect(self.btnClicked)
self.createTable()
self.create_combo_list1()
self.create_combo_list2()
self.Company.currentTextChanged.connect(self.create_combo_list2)
self.button2.clicked.connect(self.open_graph)
def initUI(self):
self.setWindowTitle('자동차 정보')
self.show()
def createTable(self):
self.tableWidget = QTableWidget(self)
self.vLayout.addWidget(self.tableWidget)
def updateTable(self, header, data):
self.tableWidget.clear()
n_row, n_col = len(data), len(header)
self.tableWidget.setRowCount(n_row)
self.tableWidget.setColumnCount(n_col)
self.tableWidget.setHorizontalHeaderLabels(header)
for row in range(n_row):
for col in range(n_col):
item = QTableWidgetItem(data[row][col])
self.tableWidget.setItem(row, col, item)
def btnClicked(self):
header = ['회사명','모델','배기량','년도', '실린더 수','변속기','구동방식', '도시연비', '고속도로연비', '연료종류', '차종']
self.new_data = []
for i in range(len(self.data)):
if (self.Company.currentText() == self.data[i][0] or self.Company.currentText() == 'All') and \
(self.Models.currentText() == self.data[i][1] or self.Models.currentText() == 'All'):
self.new_data.append(self.data[i])
self.updateTable(header, self.new_data)
def create_combo_list1(self):
company_set = set(cnt[0] for cnt in self.data)
self.Company.addItems(['All'] + list(company_set))
def create_combo_list2(self):
models = [cnt[1] for cnt in self.data if self.Company.currentText() == 'All' or self.Company.currentText() == cnt[0]]
self.Models.clear()
self.Models.addItem('All')
self.Models.addItems(set(models))
def open_graph(self):
if not Class.second_ui_instance:
Class.second_ui_instance = SecondUI(self.new_data)
Class.second_ui_instance.show()
class SecondUI(QMainWindow):
def __init__(self, new_data):
super().__init__()
self.new_data = new_data
self.main_widget = QWidget()
self.setCentralWidget(self.main_widget)
self.layout = QGridLayout(self.main_widget)
plt.rcParams['font.family'] ='Malgun Gothic'
plt.rcParams['axes.unicode_minus'] =False
canvas1 = FigureCanvas(Figure(figsize=(4, 3)))
ax1 = canvas1.figure.subplots()
self.create_graph(ax1, '연료 종류별 도시 연비 평균', '연료 종류', '도시 연비', 9, 7)
self.layout.addWidget(canvas1, 0, 0)
canvas2 = FigureCanvas(Figure(figsize=(4, 3)))
ax2 = canvas2.figure.subplots()
self.create_graph(ax2, '실린더 수별 도시 연비 평균', '실린더 수', '도시 연비', 4, 7)
self.layout.addWidget(canvas2, 0, 1)
canvas3 = FigureCanvas(Figure(figsize=(4, 3)))
ax3 = canvas3.figure.subplots()
self.create_graph(ax3, '연료 종류별 고속도로 연비 평균', '연료 종류', '고속도로 연비', 9, 8)
self.layout.addWidget(canvas3, 1, 0)
canvas4 = FigureCanvas(Figure(figsize=(4, 3)))
ax4 = canvas4.figure.subplots()
self.create_graph(ax4, '실린더 수별 고속도로 연비 평균', '실린더 수', '고속도로 연비', 4, 8)
self.layout.addWidget(canvas4, 1, 1)
self.setWindowTitle('실린더 / 연료종류 별 각종 연비 평균 그래프')
self.setGeometry(400, 30, 1200, 1000)
def closeEvent(self, event):
Class.second_ui_instance = None
super().closeEvent(event)
def create_graph(self, ax, title, xlabel, ylabel, index1, index2):
data = {}
count = {}
for i in self.new_data:
if i[9] == 'r':
i[9] = '일반유'
elif i[9] == 'p':
i[9] = '고급유'
elif i[9] == 'e':
i[9] = '에탄올 E85'
elif i[9] == 'd':
i[9] = '디젤'
elif i[9] == 'c':
i[9] = '천연가스'
else:
pass
if i[index1] in data:
data[i[index1]] += int(i[index2])
count[i[index1]] += 1
else:
data[i[index1]] = int(i[index2])
count[i[index1]] = 1
sorted_keys = sorted(data.keys())
cty = [value / count[key] for key, value in data.items()]
bars = ax.bar(sorted_keys, cty)
for bar, value in zip(bars, cty):
ax.text(bar.get_x() + bar.get_width() / 2, value, f'{value:.1f}', ha='center', va='bottom')
ax.set_title(title)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Class()
sys.exit(app.exec_())
'빅데이터 분석가 양성과정 > PyQt' 카테고리의 다른 글
위젯과 레이아웃 (2) | 2024.07.10 |
---|---|
시그널과 함수 (0) | 2024.07.10 |
시작 (0) | 2024.07.10 |