def create_initialize_histogram(self): bar_set = QBarSet('x') bar_set.append([0] * 10) max_val = 100 series = QBarSeries() series.append(bar_set) return series, max_val
def draw(self, chart_data: PieChartData) -> None: # series = QPieSeries() # for project, duration in chart_data.data.items(): # series.append("{} ({} s)".format(project, int(duration)), duration) # self.chart_view.setRenderHint(QPainter.Antialiasing) # self.chart_view.chart().removeAllSeries() # self.chart_view.chart().addSeries(series) # TODO redo with stacked bar chart series = QBarSeries() bar_set = QBarSet('Default') categories = [] for project, duration in chart_data.data.items(): if project == self.config.projects.none_project: project = 'None' categories.append(project) bar_set.append(duration) series.append(bar_set) axis_x = QBarCategoryAxis() axis_x.append(categories) self.chart.removeAllSeries() self.chart.addSeries(series) self.chart.setAxisX(axis_x) series.attachAxis(axis_x) self.initialized = True
def initChart(self, common): self.categories = [item[0] for item in common] series = QBarSeries(self._chart) bar = QBarSet("") # 随机数据 for item in common: bar.append(item[1]) series.append(bar) bar.hovered.connect(self.handleBarHoverd) # 鼠标悬停 self._chart.addSeries(series) self._chart.createDefaultAxes() # 创建默认的轴 # x轴 axis_x = QBarCategoryAxis(self._chart) axis_x.append(self.categories) self._chart.setAxisX(axis_x, series) # chart的图例 legend = self._chart.legend() legend.setVisible(True) # 遍历图例上的标记并绑定信号 for marker in legend.markers(): # 点击事件 marker.clicked.connect(self.handleMarkerClicked) # 鼠标悬停事件 marker.hovered.connect(self.handleMarkerHovered) # 一些固定计算,减少mouseMoveEvent中的计算量 # 获取x和y轴的最小最大值 axisX, axisY = self._chart.axisX(), self._chart.axisY() self.category_len = len(axisX.categories()) self.min_x, self.max_x = -0.5, self.category_len - 0.5 self.min_y, self.max_y = axisY.min(), axisY.max() # 坐标系中左上角顶点 self.point_top = self._chart.mapToPosition( QPointF(self.min_x, self.max_y)) self.setChart(self._chart)
def _init_chart(self) -> None: series = QBarSeries() axis_x = QBarCategoryAxis() axis_y = QValueAxis() data_set = defaultdict(int) for title, money in self.base: data_set[title] += money for title, money in data_set.items(): bar = QBarSet(title) axis_x.append(title) bar.append(money) series.append(bar) # self.chart = QChart() self.chart.addSeries(series) self.chart.setAnimationOptions(QChart.SeriesAnimations) # series.attachAxis(axis_x) self.chart.addAxis(axis_x, Qt.AlignBottom) axis_y.setRange(0, max(data_set.values())) axis_y.setTickCount(11) self.chart.addAxis(axis_y, Qt.AlignLeft) series.attachAxis(axis_y) # self.chart.legend().setVisible(True) self.chart.legend().setAlignment(Qt.AlignBottom)
def addSeries( self, _x2idx: typing.Dict, _idx2x: list, _chart: QChart, _axis_x: QValueAxis, _axis_y: QValueAxis, ): bar_set = QBarSet(self.name) tmp_dict = dict(zip(self.x_list, self.y_list)) for k in _idx2x: try: bar_set.append(tmp_dict[k]) except KeyError: bar_set.append(0) if self.color is not None: bar_set.setColor(self.color) bar_series = QBarSeries() bar_series.append(bar_set) _chart.addSeries(bar_series) _chart.setAxisX(_axis_x, bar_series) _chart.setAxisY(_axis_y, bar_series) if self.show_value: self.createShow()
def show_diagram(self): self.student_diagram_ui.label_4.setText(self.label_2.text()) self.student_diagram_ui.label_7.setText(self.label_8.text()) self.student_diagram_ui.label_8.setText(self.label_6.text()) self.student_diagram_ui.label_10.setText(self.label_4.text()) max_value = 0 series = QBarSeries() for i in self.result: set0 = QBarSet(i[0]) set0.append(float(i[1])) series.append(set0) if max_value < (float(i[1])): max_value = float(i[1]) axisY = QValueAxis() axisY.setRange(0, max_value) chart = QChart() series.attachAxis(axisY) chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) centralwidget = self.student_diagram_ui.centralwidget self.student_diagram_ui.chartview = QChartView(chart, centralwidget) self.student_diagram_ui.chartview.setGeometry(QtCore.QRect(10, 110, 880, 371)) self.student_diagram_ui.pushButton_3.show() self.student_diagram_ui.update(self.dark_theme) self.student_diagram_window.show()
def handler(self): ''' Processes Data ''' barset = QBarSet('Attacks') countdata = self.data.agg('count') self.max = countdata.max() now = time.localtime() past12months = [ time.localtime( time.mktime( (now.tm_year, now.tm_mon - n, 1, 0, 0, 0, 0, 0, 0)))[:2] for n in range(12) ] # get the past 12 months from current date datadict = {} for key in past12months: for k, v in countdata.items(): if k == key: datadict[k] = v # set value to 0 if no attacks in a key (month) for k in past12months: if k not in datadict.keys(): datadict[k] = 0 self.sorteddict = OrderedDict(sorted(datadict.items())) setlist = [ value for key, value in self.sorteddict.items() ] # list of attack counts over the past 12 months to append to barset barset.append(setlist) self.series = QBarSeries() self.series.setLabelsVisible(True) self.series.append(barset)
def loadWeekChart(self): try: self.weekChartView._series.clear() sql = 'select * from v_week_task_chart' datas = self.sqlite.executeQuery(sql) weekXAxis = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"] week_day_dict = { '0': '星期一', '1': '星期二', '2': '星期三', '3': '星期四', '4': '星期五', '5': '星期六', '6': '星期天', } doneBar = QBarSet('完成任务') doneBar.setColor(QColor('#F95D5C')) # 待优化循环 for week in weekXAxis: exist = False for data in datas: if week == week_day_dict[data['week']]: doneBar.append(data['count']) if data['count'] > self.weekChartView._axis_y.max(): self.weekChartView._axis_y.setRange( 0, data['count'] + 3) exist = True continue if exist == False: doneBar.append(0) self.weekChartView._series.append(doneBar) except Exception as e: self.Tips("系统异常,请查看日志") self.confstatis.error(e)
def initChart(self): self._chart = QChart(title="柱状图堆叠") self._chart.setAcceptHoverEvents(True) # Series动画 self._chart.setAnimationOptions(QChart.SeriesAnimations) self.categories = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] # names = ["邮件营销", "联盟广告", "视频广告", "直接访问", "搜索引擎"] names = ["邮件营销", ] series = QBarSeries(self._chart) for name in names: bar = QBarSet(name) # 随机数据 for _ in range(7): bar.append(randint(0, 10)) series.append(bar) bar.hovered.connect(self.handleBarHoverd) # 鼠标悬停 self._chart.addSeries(series) self._chart.createDefaultAxes() # 创建默认的轴 # x轴 axis_x = QBarCategoryAxis(self._chart) axis_x.append(self.categories) self._chart.setAxisX(axis_x, series) # chart的图例 legend = self._chart.legend() legend.setVisible(True) # 遍历图例上的标记并绑定信号 for marker in legend.markers(): # 点击事件 marker.clicked.connect(self.handleMarkerClicked) # 鼠标悬停事件 marker.hovered.connect(self.handleMarkerHovered) self.setChart(self._chart)
def create_predict_histogram(self): bar_set = QBarSet('x') hist_val, _ = self.predictor.get_hist_values() max_val = max(hist_val) bar_set.append(hist_val) series = QBarSeries() series.append(bar_set) return series, max_val
def setData(self, data): self.series.clear() for i, j in zip(data, self.brushes): barset = QBarSet("test") barset.append(i) barset.setBrush(j) barset.setPen(self.pen) self.series.append(barset)
def build(self): self.setWindowTitle("Histogram - " + self.name) self.setMinimumSize(400, 300) # Close when ctrl+w is triggered QShortcut(QKeySequence("Ctrl+W"), self, self.close) # 2D array -> 1D array img = self.image.ravel() # Process histogram histogram, bin_edges = np.histogram(img, bins='auto') bar_series = QBarSeries() bar_ = QBarSet("") # Append values for val in histogram: bar_.append(val) pen = bar_.pen() pen.setColor(Qt.black) pen.setWidth(0.1) bar_.setPen(pen) # Append bar to the bar series bar_series.append(bar_) # Chart object chart = QChart() chart.addSeries(bar_series) # Active animation chart.setAnimationOptions(QChart.SeriesAnimations) # Do not show title chart.legend().setVisible(False) # Draw Axes, with [min, max] # Y axis h_max = histogram.max() axis_y = QValueAxis() axis_y.setRange(0, h_max) # X axis be_max = bin_edges.max() be_min = bin_edges.min() axis_x = QValueAxis() axis_x.setRange(be_min, be_max) # Add axis to chart + rendering chart.addAxis(axis_x, Qt.AlignBottom) chart.addAxis(axis_y, Qt.AlignLeft) view = QChartView(chart) view.setRenderHint(QPainter.Antialiasing) self.setCentralWidget(view)
def createBar(self): min_num, max_num = 0, 100 linked_bag_list = [] try: df = self.linked['Beam Diff'].dropna() linked_bag_list = df.values.tolist() min_num = int(min(linked_bag_list)) if min_num > 0: # check if greater than 0, set to 0 min_num = 0 max_num = int(max(linked_bag_list)) except AttributeError: self.statusbar.showMessage('Data not ready') count = [0] * (max_num + 1) # choose the largest num as length of count for num in linked_bag_list: count[int(num)] += 1 # update every number's count max_count = max(count) setBar = QBarSet('Beam Difference Occurrence') setBar.append(count) brush = QBrush(QColor(0x57B1FD)) pen = QPen(QColor(0x57B1FD)) pen.setWidth(2) setBar.setPen(pen) setBar.setBrush(brush) series = QBarSeries() series.append(setBar) chart = QChart() chart.setTheme(QChart.ChartThemeBlueIcy) font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.setTitle('Linked Bins Histogram') chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) axisX = QValueAxis() axisX.setTitleText("Attenuation Window") axisX.setRange(min_num, max_num+20) chart.setAxisX(axisX, series) axisY = QValueAxis() axisY.setTitleText("Frequency") axisY.setRange(0, max_count+20) chart.setAxisY(axisY, series) chart.legend().hide() chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) return chartView
def load_glycation(self, filename: Optional[str] = None) -> None: """ Load glycation data from a CSV file and display it in the corresponding chart view. :param str filename: directly load this file :return: nothing, sets self.se_glycation :rtype: None """ # load and clean glycation data if filename is None: filename, self.last_path = get_filename( self, "open", self.tr("Load glycation data ..."), self.last_path, FileTypes(["csv"])) if filename is None: return logging.info( self.tr("Loading glycation data in '{}'").format(filename)) try: self.glycation = read_clean_datasets(filename) except (OSError, ValueError) as e: logging.error(str(e)) QMessageBox.critical(self, self.tr("Error"), str(e)) return # extract x- and y-values from series x_values = [str(i) for i in self.glycation.index] y_values = [a.nominal_value for a in self.glycation] # assemble the chart bar_set = QBarSet("glycation abundance") bar_set.append(y_values) bar_set.setColor(QColor("#a1dab4")) bar_set.hovered.connect(self.update_glycation_label) bar_series = QBarSeries() bar_series.append(bar_set) x_axis = QBarCategoryAxis() x_axis.append(x_values) x_axis.setTitleText(self.tr("count")) y_axis = QValueAxis() y_axis.setRange(0, 100) y_axis.setTitleText(self.tr("abundance")) y_axis.setLabelFormat("%d") chart = QChart() chart.addSeries(bar_series) chart.setAxisX(x_axis, bar_series) chart.setAxisY(y_axis, bar_series) chart.legend().setVisible(False) chart.setBackgroundRoundness(0) chart.layout().setContentsMargins(0, 0, 0, 0) chart.setMargins(QMargins(5, 5, 5, 5)) self.cvGlycation.setChart(chart)
def beforeDelay(self): print("in before delay bar") min_num, max_num = 0, 100 max_count = 0 total_stopped_time = [] try: total_stopped_time = self.tm.total_stopped_time max_num = max(total_stopped_time) except AttributeError: self.statusbar.showMessage('Data not ready') count = total_stopped_time count = [0] * (int(max_num) + 1 ) # choose the largest num as length of count for num in total_stopped_time: count[int(num)] += 1 # update every number's count max_count = max(count) print(len(total_stopped_time), max_count) setBar = QBarSet('stop time') setBar.append(count) brush = QBrush(QColor(0x57B1FD)) pen = QPen(QColor(0x57B1FD)) pen.setWidth(2) setBar.setPen(pen) setBar.setBrush(brush) series = QBarSeries() series.append(setBar) chart = QChart() font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.setTitle('Stop time Histogram (before)') chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) axisX = QValueAxis() axisX.setRange(min_num, max_num + 20) chart.setAxisX(axisX, series) axisY = QValueAxis() axisY.setRange(0, max_count + 20) chart.setAxisY(axisY, series) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) # MainWindow.setCentralWidget(chartView) return chartView
def update_boat_speed_plot(self): # Create new bar set new_bar_set = QBarSet(str(self.seen_strokes)) value = self.boat_speed_data[-1] value_rel = int(value * 255 / self.BOAT_SPEED_PLOT_MAX_Y) new_bar_set.append(value) new_bar_set.setColor(self.COLOR_BLUE) # QColor(value_rel, value_rel, value_rel)) # Append new set, and remove oldest self.boat_speed_plot_series.append(new_bar_set) self.boat_speed_plot_series.remove(self.boat_speed_plot_series.barSets()[0])
def afterDelay(self): # print("in after delay bar") min_num, max_num = 0, 100 max_count = 0 total_stopped_after_delay = [] count = [0] * (int(max_num) + 1) # choose the largest num as length of count try: total_stopped_after_delay = self.tm.total_stopped_after_delay max_num = max(total_stopped_after_delay) count = [0] * (int(max_num) + 1) # choose the largest num as length of count for num in total_stopped_after_delay: count[int(num)] += 1 # update every number's count max_count = max(count) except (AttributeError, ValueError): self.statusbar.showMessage('Data not ready') setBar = QBarSet('Stop Time Occurrence') setBar.append(count) brush = QBrush(QColor(0xA6E22E)) # Green pen = QPen(QColor(0xA6E22E)) # Green pen.setWidth(2) setBar.setPen(pen) setBar.setBrush(brush) series = QBarSeries() series.append(setBar) chart = QChart() font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.setTitle('Stop time Occurrence (after)') chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) axisX = QValueAxis() axisX.setRange(min_num, max_num+20) chart.setAxisX(axisX, series) axisY = QValueAxis() axisY.setRange(0, max_count+20) chart.setAxisY(axisY, series) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) # MainWindow.setCentralWidget(chartView) return chartView
def agg_glycoforms(self) -> None: """ Display glycoform data in the corresponding chart view. :return: nothing :rtype: None """ # aggregate "other" abundances if self.cbAggGlycoforms.isChecked(): agg_abundance = ( self.glycoforms.iloc[self.sbAggGlycoforms.value():].sum()) self.glycoforms_agg = ( self.glycoforms.iloc[:self.sbAggGlycoforms.value()].append( pd.Series(agg_abundance, index=[self.tr("other")]))) else: self.glycoforms_agg = self.glycoforms # extract x- and y-values from series x_values = [str(i) for i in self.glycoforms_agg.index] y_values = [a.nominal_value for a in self.glycoforms_agg] # assemble the chart bar_set = QBarSet("glycoform abundance") bar_set.append(y_values) bar_set.setColor(QColor("#2c7fb8")) bar_set.hovered.connect(self.update_glycoform_label) bar_series = QBarSeries() bar_series.append(bar_set) x_axis = QBarCategoryAxis() x_axis.append(x_values) x_axis.setTitleVisible(False) x_axis.setLabelsAngle(270) range_max = max(self.glycoforms_agg).nominal_value range_max = math.ceil(range_max / 20) * 20 tick_count = range_max // 20 + 1 y_axis = QValueAxis() y_axis.setRange(0, range_max) y_axis.setTickCount(tick_count) y_axis.setTitleText(self.tr("abundance")) y_axis.setLabelFormat("%d") chart = QChart() chart.addSeries(bar_series) chart.setAxisX(x_axis, bar_series) chart.setAxisY(y_axis, bar_series) chart.legend().setVisible(False) chart.setBackgroundRoundness(0) chart.layout().setContentsMargins(0, 0, 0, 0) chart.setMargins(QMargins(5, 5, 5, 5)) self.cvGlycoforms.setChart(chart)
def ageWiseBarGraph(self): self.w = Window2() self.w.show() set0 = QBarSet('below 25') set1 = QBarSet('25 to 35') set2 = QBarSet('36 to 45') set3 = QBarSet('46 to 55') set4 = QBarSet('above 55') file="killings.csv" ageSet = [0,0,0,0,0] with open('killings.csv') as File: csvReader = csv.reader(File) next(csvReader) for row in csvReader: if int(row[5]) < 25: ageSet[0]+=1 elif int(row[5]) >=25 and int(row[5])<= 35: ageSet[1]+=1 elif int(row[5]) >35 and int(row[5])<=45: ageSet[2]+=1 elif int(row[5]) >45 and int(row[5])<= 55: ageSet[3]+=1 else: ageSet[4]+=1 print (ageSet) set0.append(ageSet[0]) set1.append(ageSet[1]) set2.append(ageSet[2]) set3.append(ageSet[3]) set4.append(ageSet[4]) series = QBarSeries() series.append(set0) series.append(set1) series.append(set2) series.append(set3) series.append(set4) chart = QChart() chart.addSeries(series) chart.setTitle('Age wise comparison') chart.setAnimationOptions(QChart.SeriesAnimations) msg = ('Death Toll') axisX = QBarCategoryAxis() axisX.append(msg) axisY = QValueAxis() axisY.setRange(0, 200) chart.addAxis(axisX, Qt.AlignBottom) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) self.w.setCentralWidget(chartView)
def _create_series_barchart(self, correct_bot, correct_human, incorrect_bot, incorrect_human): correct_set = QBarSet('Correct Prediction') correct_set.append([correct_human, correct_bot]) correct_set.setColor(QColor("#29ec1e")) incorrect_set = QBarSet('Incorrect Prediction') incorrect_set.append([incorrect_human, incorrect_bot]) incorrect_set.setColor(QColor("#ED213A")) series = QBarSeries() series.append(correct_set) series.append(incorrect_set) return series
def beforeDelayDistribution(self): min_num, max_num = 0, 100 max_count = 0 total_stopped_time = [] count = [0] try: total_stopped_time = self.tm.total_stopped_time max_num = len(total_stopped_time) # change from max() to len() 2/12 11:11 count = total_stopped_time max_count = max(count) except (AttributeError, ValueError): self.statusbar.showMessage('Data not ready') setBar = QBarSet('stop time') setBar.append(count) brush = QBrush(QColor(0x57B1FD)) pen = QPen(QColor(0x57B1FD)) pen.setWidth(2) setBar.setPen(pen) setBar.setBrush(brush) series = QBarSeries() series.append(setBar) chart = QChart() font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.setTitle('Stop time Distribution (before)') chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) axisX = QValueAxis() axisX.setRange(min_num, max_num) chart.setAxisX(axisX, series) axisY = QValueAxis() axisY.setRange(0, max_count+20) chart.setAxisY(axisY, series) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) # MainWindow.setCentralWidget(chartView) return chartView
def crearGraficoBarras(self): paises = [ "EEUU", "China", "Japon", "Alemania", "Reino Unido", "Resto del mundo" ] valores = [24.32, 14.85, 8.91, 12.54, 7.85, 31.53] colores = [ Qt.blue, Qt.red, Qt.darkYellow, Qt.gray, Qt.black, Qt.darkCyan ] grafico = QChart() grafico.setMargins(QMargins(30, 30, 30, 30)) grafico.setTheme(QChart.ChartThemeLight) grafico.setTitle("% Distribución del PIB global") grafico.setAnimationOptions(QChart.SeriesAnimations) for i in range(len(paises)): series = QBarSeries() barSet = QBarSet(paises[i]) barSet.setColor(colores[i]) barSet.setLabelColor(Qt.yellow) barSet.append(valores[i]) series.append(barSet) series.setLabelsVisible(True) series.setLabelsAngle(-90) # series.setLabelsPrecision(2) series.setLabelsFormat("@value %") series.setLabelsPosition(QAbstractBarSeries.LabelsCenter) grafico.addSeries(series) axisX = QBarCategoryAxis() axisX.append(paises) axisY = QValueAxis() axisY.setRange(0, 31.53) axisY.setTickCount(10) axisY.setLabelFormat("%.2f %") grafico.createDefaultAxes() grafico.setAxisX(axisX, None) grafico.setAxisY(axisY, None) grafico.legend().setVisible(True) grafico.legend().setAlignment(Qt.AlignBottom) return grafico
def ALL(self): self.ind = 0 set0 = QBarSet('Daya Tarik') set1 = QBarSet('Aksesbilitas') set2 = QBarSet('Kebersihan') set3 = QBarSet('Fasilitas') set0.setColor(QtGui.QColor("blue")) set1.setColor(QtGui.QColor("red")) set2.setColor(QtGui.QColor("green")) set3.setColor(QtGui.QColor("orange")) gf = Grafik_2() jml = gf.jumlah_per_pantai() jml_pantai = [] for i in range(len(jml)): jml_pantai.append(jml[i]) hasil = gf.hasil_dayatarik() for i in range(len(hasil)): set0.append((hasil[i] / jml_pantai[i]) * 100) hasil2 = gf.hasil_aksesbilitas() for i in range(len(hasil2)): set1.append((hasil2[i] / jml_pantai[i]) * 100) hasil3 = gf.hasil_kebersihan() for i in range(len(hasil3)): set2.append((hasil3[i] / jml_pantai[i]) * 100) hasil4 = gf.hasil_fasilitas() for i in range(len(hasil4)): set3.append((hasil4[i] / jml_pantai[i]) * 100) series = QBarSeries() series.append(set0) series.append(set1) series.append(set2) series.append(set3) series.setLabelsVisible(True) series.setLabelsPosition(QAbstractBarSeries.LabelsInsideEnd) series.setLabelsAngle(-90) self.chart = QChart() self.chart.addSeries(series) self.chart.setTitle('Grafik Prosentase Ulasan Pantai') self.chart.setAnimationOptions(QChart.SeriesAnimations) axisY = QValueAxis() axisY.setTitleText("Prosentase (%)") axisY.applyNiceNumbers() self.chart.addAxis(axisY, Qt.AlignLeft) series.attachAxis(axisY) self.chart.legend().setVisible(True) self.chart.legend().setAlignment(Qt.AlignBottom) self.chart.createDefaultAxes() self.graphicsView.setChart(self.chart) self.adjust_axes(0, 2) self.lims = np.array([0, 6]) self.onAxisSliderMoved(self.verticalScrollBar.value())
def loadMonthChart(self, year='', month=''): try: self.monthChartView._series.clear() self.monthChartView._axis_x.clear() if year == '': year = datetime.now().strftime('%Y') if month == '': month = datetime.now().strftime('%m') monthRange = calendar.monthrange(int(year), int(month)) dates = [] cats = [] for i in range(monthRange[1]): dates.append(str(i + 1)) cats.append(str(i + 1) + '日') self.monthChartView._axis_x.append(dates) self.monthChartView._axis_x.setTitleText('日期') self.monthChartView.setCat(cats) self.monthChartView.cal() sql = ''' SELECT count( * ) as count, CAST(strftime('%d',tbt.finish_date)as int) as day FROM t_base_task tbt WHERE tbt.is_finish = 1 AND strftime('%m',tbt.finish_date) = ? AND strftime('%Y',tbt.finish_date) = ? group by strftime('%m',tbt.finish_date) ''' datas = self.sqlite.executeQuery(sql, [month, year]) doneBar = QBarSet('完成任务') doneBar.setColor(QColor('#F95D5C')) # 待优化循环 for date in dates: exist = False for data in datas: if date == str(data['day']): doneBar.append(data['count']) if data['count'] > self.weekChartView._axis_y.max(): self.monthChartView._axis_y.setRange( 0, data['count'] + 3) exist = True continue if exist == False: doneBar.append(0) self.monthChartView._series.append(doneBar) except Exception as e: self.Tips("系统异常,请查看日志") self.confstatis.error(e)
def __init__(self): super().__init__() self.resize(800, 600) set0 = QBarSet('X0') set1 = QBarSet('X1') set2 = QBarSet('X2') set3 = QBarSet('X3') set4 = QBarSet('X4') set0.append([1, 2, 3, 4, 5, 6]) set1.append([5, 0, 0, 4, 0, 7]) set2.append([3, 5, 8, 13, 8, 5]) set3.append([5, 6, 7, 3, 4, 5]) set4.append([9, 7, 5, 3, 1, 2]) series = QHorizontalBarSeries() series.append(set0) series.append(set1) series.append(set2) series.append(set3) series.append(set4) chart = QChart() chart.addSeries(series) chart.setTitle('Horizontal Bar Chart Demo') chart.setAnimationOptions(QChart.SeriesAnimations) months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June') axisY = QBarCategoryAxis() axisY.append(months) chart.addAxis(axisY, Qt.AlignLeft) series.attachAxis(axisY) axisX = QValueAxis() chart.addAxis(axisX, Qt.AlignBottom) series.attachAxis(axisX) axisX.applyNiceNumbers() chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) self.setCentralWidget(chartView)
def DT(self): self.ind = 1 gf = Grafik_2() jml = gf.jumlah_per_pantai() jml_pantai = [] for i in range(len(jml)): jml_pantai.append(jml[i]) value = [] hasil = gf.hasil_dayatarik() for i in range(len(hasil)): value.append((hasil[i] / jml_pantai[i]) * 100) sorting = sorted(value, reverse=True) index = np.argsort(value)[::-1] label_sorting = [] for i in index: label_sorting.append(self.label_pantai[i]) set0 = QBarSet('Daya Tarik') set0.setColor(QtGui.QColor("blue")) for i in range(len(hasil)): set0.append(sorting) series = QBarSeries() series.append(set0) series.setLabelsVisible(True) series.setLabelsPosition(QAbstractBarSeries.LabelsInsideEnd) self.chart = QChart() self.chart.addSeries(series) self.chart.setTitle('Grafik Prosentase Ulasan Pantai') self.chart.setAnimationOptions(QChart.SeriesAnimations) axisX = QBarCategoryAxis() axisX.setLabelsAngle(-90) axisY = QValueAxis() axisY.setTitleText("Prosentase (%)") self.chart.addAxis(axisX, Qt.AlignBottom) self.chart.addAxis(axisY, Qt.AlignLeft) series.attachAxis(axisY) axisY.applyNiceNumbers() self.chart.legend().setVisible(True) self.chart.legend().setAlignment(Qt.AlignBottom) self.chart.createDefaultAxes() self.graphicsView.setChart(self.chart) self.lims = np.array([0, 10]) self.onAxisSliderMoved(self.verticalScrollBar.value())
def _create_revision_count_graph(self): stats = CollectionStats(self.col) categories_labels = list(range(-30, 1, 1)) data = stats.revision_count_stats() data = self._transform_first_column_to_key(data) data = self._add_default_value_for_missing_keys( data, [0, 0, 0, 0, 0], categories_labels) series = QStackedBarSeries(self) setLearning = QBarSet("Learning", self) [setLearning.append(row[0]) for row in data] setYoung = QBarSet("Young", self) [setYoung.append(row[1]) for row in data] setMature = QBarSet("Mature", self) [setMature.append(row[2]) for row in data] setLapse = QBarSet("Lapse", self) [setLapse.append(row[3]) for row in data] setEarly = QBarSet("Early", self) [setEarly.append(row[4]) for row in data] categories = QBarCategoryAxis() categories.setCategories([str(-i) for i in categories_labels]) series.append(setLearning) series.append(setYoung) series.append(setMature) series.append(setLapse) series.append(setEarly) chart = QChart() chart.addSeries(series) chart.createDefaultAxes() chart.setAxisX(categories, series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle("Number of cards reviewed recently") chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartview = QChartView(chart) chartview.setRenderHint(QPainter.Antialiasing) self.layout.addWidget(chartview)
def _create_reviews_due_chart(self): ## TODO: later replace by date selector start, end, chunk = 0, 31, 1 stats = CollectionStats(self.col) ## TODO: refactor stats._due categories_labels = list(range(0, 31, 1)) data = stats.due(start, end, chunk) data = self._transform_first_column_to_key(data) data = self._add_default_value_for_missing_keys( data, [0, 0, 0, 0], categories_labels) series = QStackedBarSeries(self) setYoung = QBarSet("Young", self) [setYoung.append(row[0]) for row in data] setAdolescent = QBarSet("Adolescent", self) [setAdolescent.append(row[1]) for row in data] setMature = QBarSet("Mature", self) [setMature.append(row[2]) for row in data] setOld = QBarSet("Old", self) [setOld.append(row[3]) for row in data] categories = QBarCategoryAxis() categories.setCategories([str(i) for i in categories_labels]) series.append(setOld) series.append(setMature) series.append(setAdolescent) series.append(setYoung) chart = QChart() chart.addSeries(series) chart.createDefaultAxes() chart.setAxisX(categories, series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle("Forecast: the number of reviews due in the future") chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartview = QChartView(chart) chartview.setRenderHint(QPainter.Antialiasing) self.layout.addWidget(chartview)
def __init__(self): super().__init__() self.resize(800, 600) set0 = QBarSet('X0') set1 = QBarSet('X1') set2 = QBarSet('X2') set3 = QBarSet('X3') set4 = QBarSet('X4') set0.append([random.randint(0, 10) for i in range(6)]) set1.append([random.randint(0, 10) for i in range(6)]) set2.append([random.randint(0, 10) for i in range(6)]) set3.append([random.randint(0, 10) for i in range(6)]) set4.append([random.randint(0, 10) for i in range(6)]) series = QBarSeries() series.append(set0) series.append(set1) series.append(set2) series.append(set3) series.append(set4) chart = QChart() chart.addSeries(series) chart.setTitle('Bar Chart Demo') chart.setAnimationOptions(QChart.SeriesAnimations) months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun') axisX = QBarCategoryAxis() axisX.append(months) axisY = QValueAxis() axisY.setRange(0, 15) chart.addAxis(axisX, Qt.AlignBottom) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) self.setCentralWidget(chartView)
def compile_torrent_charts(self, db_rows): """ Factory method for generating charts. Input -> All database rows for a single torrent. Output -> Line and Bar Charts for Ratio and Upload. """ line_series = QLineSeries() ul_series = QBarSeries() ratio_series = QBarSeries() ulset = QBarSet("Uploaded") ratioset = QBarSet("Ratio") """ Generate empty bar and line charts for data series. """ seq = [] ul_top, ratio_top = 0, 0 ul_last, skip_count = 0, 0 for i, row in enumerate(db_rows): ul = row["uploaded"] ratio = row["ratio"] """ Compare current iteration to previous and skip if values most of the measured values are identical to avoid clutter. """ if ul == ul_last and skip_count < 6: skip_count += 1 continue skip_count = 0 ul_last = ul if ul > ul_top: ul_top, ratio_top = ul, ratio ulset.append(ul) ratioset.append(ratio) """ Change IsoFormatted time into a more compact datetime format. """ stamp = self.convert_stamp(row["timestamp"]) seq.append(stamp) ul_series.append(ulset) ratio_series.append(ratioset) line_chart = self.get_diff_chart(line_series, db_rows) ul_chart = self.form_chart(ul_series, "Uploaded", seq, ul_top) ratio_chart = self.form_chart(ratio_series, "Ratio", seq, ratio_top) return ul_chart, ratio_chart, line_chart
def addSeries( self, _x2idx: typing.Dict, _idx2x: list, _chart: QChart, _axis_x: QValueAxis, _axis_y: QValueAxis ): bar_set = QBarSet(self.name) tmp_dict = dict(zip(self.x_list, self.y_list)) for k in _idx2x: if k in tmp_dict.keys(): bar_set.append(tmp_dict[k]) else: bar_set.append(0) if self.color is not None: bar_set.setColor(self.color) bar_series = QBarSeries() bar_series.append(bar_set) _chart.addSeries(bar_series) _chart.setAxisX(_axis_x, bar_series) _chart.setAxisY(_axis_y, bar_series) if self.show_value: self.createShow()