Exemplo n.º 1
0
    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()
Exemplo n.º 2
0
 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)
Exemplo n.º 3
0
    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)
Exemplo n.º 4
0
 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])
Exemplo n.º 5
0
    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)
Exemplo n.º 6
0
    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
Exemplo n.º 7
0
    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
Exemplo n.º 8
0
    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())
Exemplo n.º 9
0
 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)
Exemplo n.º 10
0
    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())
Exemplo n.º 11
0
    def initChart(self):
        self._chart = QChart(title='数量')
        self._chart.setAnimationOptions(QChart.SeriesAnimations)
        series = QStackedBarSeries()
        series.setName('数量')
        bar_red = QBarSet('red')
        bar_red.setColor(Qt.red)
        bar_green = QBarSet('green')
        bar_green.setColor(Qt.green)
        for _, stock in self.stocks.iterrows():
            if stock['open'] < stock['close']:
                bar_red.append(stock['vol'] / 100)
                bar_green.append(0)
            else:
                bar_red.append(0)
                bar_green.append(stock['vol'] / 100)

        series.append(bar_red)
        series.append(bar_green)
        self._chart.addSeries(series)
        self._chart.createDefaultAxes()
        self._chart.setLocalizeNumbers(True)
        axis_x = self._chart.axisX()
        axis_y = self._chart.axisY()
        axis_x.setGridLineVisible(False)
        axis_y.setGridLineVisible(False)
        axis_y.setLabelFormat("%.2f")
        axis_x.setCategories(self.category)
        max_p = self.stocks[[
            'vol',
        ]].stack().max() / 100 + 10
        min_p = self.stocks[[
            'vol',
        ]].stack().min() / 100 - 10
        axis_y.setRange(min_p, max_p)

        # chart的图例
        legend = self._chart.legend()
        legend.hide()
        # 设置图例由Series来决定样式
        # legend.setMarkerShape(QLegend.MarkerShapeFromSeries)

        self.setChart(self._chart)
        self._chart.layout().setContentsMargins(0, 0, 0, 0)
        # self._chart.setMargins(QMargins(0, 0, 0, 0))
        self._chart.setBackgroundRoundness(0)
Exemplo n.º 12
0
    def loadYearTotalChart(self):
        try:
            self.yearTotalView._series.clear()
            sql = 'select * from v_year_total_count'
            datas = self.sqlite.executeQuery(sql)
            yearXAxis = [
                "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月",
                "十一月", "十二月"
            ]
            month_day_dict = {
                '01': '一月',
                '02': '二月',
                '03': '三月',
                '04': '四月',
                '05': '五月',
                '06': '六月',
                '07': '七月',
                '08': '八月',
                '09': '九月',
                '10': '十月',
                '11': '十一月',
                '12': '十二月',
            }
            doneBar = QBarSet('按时完成')
            doneBar.setColor(QColor('#F95D5C'))
            overdueBar = QBarSet('逾期完成')
            overdueBar.setColor(QColor('#aa3e3e'))
            # 待优化循环
            for month in yearXAxis:
                exist = False
                for data in datas:
                    if month == month_day_dict[data['month']]:
                        doneBar.append(data['done'])
                        overdueBar.append(data['overdue'])
                        exist = True
                        continue
                if exist == False:
                    doneBar.append(0)
                    overdueBar.append(0)
            self.yearTotalView._series.append(doneBar)
            self.yearTotalView._series.append(overdueBar)

        except Exception as e:
            self.Tips("系统异常,请查看日志")
            self.confstatis.error(e)
Exemplo n.º 13
0
class QtBarChart(QChartView):
    def __init__(self, spec):
        super().__init__(None)
        self.spec = spec
        self.chart = QChart()
        # self.chart.setTitle(str(self.spec.variables))
        self.chart.legend().hide()
        self.mainset = QBarSet("")
        self.mainset.append([0 for i in range(len(spec.variables))])
        self.mainset.setColor(
            QColor(spec.color[0], spec.color[1], spec.color[2]))
        self.series = QBarSeries()
        self.series.append(self.mainset)

        self.setMinimumWidth(400)
        self.setMinimumHeight(230)

        self.axis_x = QBarCategoryAxis()
        self.axis_y = QValueAxis()
        self.axis_x.append(spec.variables)
        self.chart.addSeries(self.series)
        self.chart.setAxisX(self.axis_x, self.series)
        self.chart.setAxisY(self.axis_y, self.series)

        self.setChart(self.chart)
        self.setRenderHint(QPainter.Antialiasing)

        self._updates_per_second = 10
        self._dataset = []

    def clear(self):
        self._dataset = []

    def update_data(self, dataset):
        data = []
        for d in dataset:
            data.append(d)
        self._dataset = data

    def redraw(self):
        if len(self._dataset) > 0:
            for i in range(len(self._dataset)):
                self.mainset.replace(i, self._dataset[i])
            self.axis_y.setRange(0, max(self._dataset))
Exemplo n.º 14
0
    def KB(self):
        self.ind = 3
        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_kebersihan()
        for i in range(len(hasil)):
            value.append((hasil[i] / jml_pantai[i]) * 100)
        sorting = sorted(value, reverse=True)

        set0 = QBarSet('Kebersihan')
        set0.setColor(QtGui.QColor("green"))
        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)

        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, 10])
        self.onAxisSliderMoved(self.verticalScrollBar.value())
Exemplo n.º 15
0
    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()
Exemplo n.º 16
0
    def add_series_values(self, data: pd.DataFrame, is_init=False):
        self._stocks = data
        bar_red = QBarSet('red')
        bar_red.setColor(Qt.red)
        bar_green = QBarSet('green')
        bar_green.setColor(Qt.green)
        for _, stock in self._stocks.iterrows():
            if stock['open'] < stock['close']:
                bar_red.append(stock['vol'] / self._vol_multiple)
                bar_green.append(0)
            else:
                bar_red.append(0)
                bar_green.append(stock['vol'] / self._vol_multiple)

        self._series.append(bar_red)
        self._series.append(bar_green)

        if not is_init:
            self._stocks = data
            self._category = self._stocks['trade_date']
            axis_x = self._chart.axisX()
            axis_y = self._chart.axisY()
            axis_x.setCategories(self._category)
            max_p = self._stocks[[
                'vol',
            ]].stack().max()
            min_p = self._stocks[[
                'vol',
            ]].stack().min()
            axis_y.setRange(min_p / self._vol_multiple * 0.9,
                            max_p / self._vol_multiple * 1.1)
            self._zero_value = (0, self._chart.axisY().min())
            self._max_value = (len(self._chart.axisX().categories()),
                               self._chart.axisY().max())
            # 计算x轴单个cate的宽度,用来处理横线不能画到边界
            self._cate_width = (self._max_point.x() -
                                self._zero_point.x()) / len(self._category)
Exemplo n.º 17
0
    def grafik_uji_kategori(self):
        with open(
                'C:/Users/asus/Desktop/SKRIPSWEET BISMILLAH/MODUL PROGRAM/Modul Program Bismillah/Pengujian/hasil_uji_kategori_kfold.json'
        ) as f:
            dataa = json.load(f)
        print(dataa)
        acc = dataa['acc']
        pres = dataa['presisi']
        rec = dataa['recall']
        set0 = QBarSet('Akurasi')
        set1 = QBarSet('Presisi')
        set2 = QBarSet('Recall')

        for i in range(len(acc)):
            set0.append(acc[i] * 100)

        for i in range(len(pres)):
            set1.append(pres[i] * 100)

        for i in range(len(rec)):
            set2.append(rec[i] * 100)

        series = QBarSeries()
        series.append(set0)
        series.append(set1)
        series.append(set2)
        set0.setColor(QtGui.QColor("navy"))
        set1.setColor(QtGui.QColor("yellow"))
        set2.setColor(QtGui.QColor("red"))

        chart = QChart()
        chart.addSeries(series)
        chart.setAnimationOptions(QChart.SeriesAnimations)
        label_pantai = ['K=1', 'K=2', 'K=3', 'K=4', 'K=5']
        axisX = QBarCategoryAxis()
        axisX.append(label_pantai)
        axisX.setLabelsAngle(0)
        axisY = QValueAxis()
        axisX.setTitleText("K-Fold Cross Validation")
        axisY.setTitleText("Prosentase (%)")
        axisY.setRange(0, max(set0))
        axisY.setMinorTickCount(5)

        chart.addAxis(axisX, Qt.AlignBottom)
        chart.addAxis(axisY, Qt.AlignLeft)
        chart.legend().setVisible(True)
        chart.legend().setAlignment(Qt.AlignBottom)
        return (chart)
Exemplo n.º 18
0
    def agg_results(self) -> None:
        """
        Display results in the corresponding chart view.

        :return: nothing
        :rtype: None
        """

        # aggregate "other" abundances
        if self.cbAggResults.isChecked():
            agg_abundance = (
                self.results.iloc[self.sbAggResults.value():].sum())
            agg_abundance["glycoform"] = self.tr("other")
            self.results_agg = (
                self.results.iloc[:self.sbAggResults.value()].append(
                    agg_abundance, ignore_index=True))
        else:
            self.results_agg = self.results

        # extract x- and y-values from series
        x_values = list(self.results_agg["glycoform"].str.split(" or").str[0])
        y_values_obs = list(self.results_agg["abundance"])
        y_values_cor = list(self.results_agg["corr_abundance"])

        # assemble the chart
        bar_set_obs = QBarSet(self.tr("observed"))
        bar_set_obs.append(y_values_obs)
        bar_set_obs.setColor(QColor("#225ea8"))
        bar_set_obs.hovered.connect(self.update_results_label)
        bar_set_cor = QBarSet(self.tr("corrected"))
        bar_set_cor.append(y_values_cor)
        bar_set_cor.setColor(QColor("#41b6c4"))
        bar_set_cor.hovered.connect(self.update_results_label)
        bar_series = QBarSeries()
        bar_series.append([bar_set_obs, bar_set_cor])

        x_axis = QBarCategoryAxis()
        x_axis.append(x_values)
        x_axis.setTitleVisible(False)
        x_axis.setLabelsAngle(270)

        range_min = min(
            self.results_agg[["abundance", "corr_abundance"]].min().min(), 0)
        range_min = math.floor(range_min / 20) * 20
        range_max = (self.results_agg[["abundance",
                                       "corr_abundance"]].max().max())
        range_max = math.ceil(range_max / 20) * 20
        tick_count = (range_max - range_min) // 20 + 1
        y_axis = QValueAxis()
        y_axis.setRange(range_min, 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.cvResults.setChart(chart)
Exemplo n.º 19
0
    def analysisUI(self, smwui):

        btn_refresh = QPushButton('Refresh')
        btn_refresh.clicked.connect(smwui.update_chart)

        smwui.cb_targetAxis1 = QCheckBox('X : Horizontal action')
        smwui.cb_targetAxis1.setChecked(True)
        smwui.cb_targetAxis1.stateChanged.connect(smwui.update_chart)
        smwui.cb_targetAxis2 = QCheckBox('Y : Vertical action')
        smwui.cb_targetAxis2.setChecked(True)
        smwui.cb_targetAxis2.stateChanged.connect(smwui.update_chart)
        smwui.cb_targetAxis3 = QCheckBox('Z : Depth action')
        smwui.cb_targetAxis3.setChecked(True)
        smwui.cb_targetAxis3.stateChanged.connect(smwui.update_chart)

        smwui.cb_targetValue1 = QCheckBox('Head')
        smwui.cb_targetValue1.setChecked(True)
        smwui.cb_targetValue2 = QCheckBox('ShoulderRight')
        smwui.cb_targetValue3 = QCheckBox('ElbowRight')
        smwui.cb_targetValue4 = QCheckBox('HandRight')
        smwui.cb_targetValue4.setChecked(True)
        smwui.cb_targetValue5 = QCheckBox('SpineBase')
        smwui.cb_targetValue6 = QCheckBox('HandLeft')
        smwui.cb_targetValue6.setChecked(True)
        smwui.cb_targetValue7 = QCheckBox('ElbowLeft')
        smwui.cb_targetValue8 = QCheckBox('ShoulderLeft')
        smwui.cb_targetValue9 = QCheckBox('Neck')
        smwui.cb_targetValue1.stateChanged.connect(smwui.update_chart)
        smwui.cb_targetValue2.stateChanged.connect(smwui.update_chart)
        smwui.cb_targetValue3.stateChanged.connect(smwui.update_chart)
        smwui.cb_targetValue4.stateChanged.connect(smwui.update_chart)
        smwui.cb_targetValue5.stateChanged.connect(smwui.update_chart)
        smwui.cb_targetValue6.stateChanged.connect(smwui.update_chart)
        smwui.cb_targetValue7.stateChanged.connect(smwui.update_chart)
        smwui.cb_targetValue8.stateChanged.connect(smwui.update_chart)
        smwui.cb_targetValue9.stateChanged.connect(smwui.update_chart)

        ### chart
        set1 = QBarSet("X")
        set2 = QBarSet("Y")
        set3 = QBarSet("Z")
        set1.setColor(QColor(0, 0, 200, 150))
        set2.setColor(QColor(0, 200, 0, 150))
        set3.setColor(QColor(200, 50, 0, 150))

        series = QHorizontalBarSeries()
        series.append(set1)
        series.append(set2)
        series.append(set3)

        categories = []
        categories.append('Parts')
        axisX = QValueAxis()
        axisX.applyNiceNumbers()
        axisY = QBarCategoryAxis()
        axisY.append(categories)

        chart = QChart()
        chart.addSeries(series)
        chart.setTitle("Timeseries Distance")
        chart.setAnimationOptions(QChart.SeriesAnimations)
        chart.setAxisX(axisX, series)
        chart.setAxisY(axisY)
        chart.legend().setVisible(True)
        chart.legend().setAlignment(Qt.AlignTop)

        smwui.chartView = QChartView(chart)
        smwui.chartView.setRenderHint(QPainter.Antialiasing)

        ### draw parts
        smwui.viewParts = QQuickWidget()
        smwui.viewParts.setSource(QUrl("./qml/qmlptviewer/main.qml"))
        smwui.viewParts.rootContext().setContextProperty(
            "HandRight", "0,0,0,0")
        smwui.viewParts.rootContext().setContextProperty("HandLeft", "0,0,0,0")
        smwui.viewParts.rootContext().setContextProperty(
            "ElbowRight", "0,0,0,0")
        smwui.viewParts.rootContext().setContextProperty(
            "ElbowLeft", "0,0,0,0")
        smwui.viewParts.rootContext().setContextProperty("Head", "0,0,0,0")
        scrollArea_viewParts = QScrollArea()
        scrollArea_viewParts.setMinimumWidth(420)
        scrollArea_viewParts.setWidget(smwui.viewParts)
        scrollArea_viewParts.setSizePolicy(QSizePolicy.Minimum,
                                           QSizePolicy.Minimum)

        ### |1|
        vbox1 = QVBoxLayout()
        vbox1.addWidget(smwui.cb_targetAxis1)
        vbox1.addWidget(smwui.cb_targetAxis2)
        vbox1.addWidget(smwui.cb_targetAxis3)
        gb_targetAxis = QGroupBox()
        gb_targetAxis.setTitle('Axis')
        gb_targetAxis.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum)
        gb_targetAxis.setLayout(vbox1)

        ### |2|
        vbox2 = QVBoxLayout()
        vbox2.addWidget(smwui.cb_targetValue1)
        vbox2.addWidget(smwui.cb_targetValue2)
        vbox2.addWidget(smwui.cb_targetValue3)
        vbox2.addWidget(smwui.cb_targetValue4)
        vbox2.addWidget(smwui.cb_targetValue5)
        vbox2.addWidget(smwui.cb_targetValue6)
        vbox2.addWidget(smwui.cb_targetValue7)
        vbox2.addWidget(smwui.cb_targetValue8)
        vbox2.addWidget(smwui.cb_targetValue9)
        gb_targetValue = QGroupBox()
        gb_targetValue.setTitle('Parts')
        gb_targetValue.setLayout(vbox2)

        vbox3 = QVBoxLayout()
        vbox3.addWidget(btn_refresh)
        vbox3.addWidget(gb_targetAxis)
        vbox3.addWidget(gb_targetValue)

        ### -1-
        hbox = QHBoxLayout()
        hbox.addLayout(vbox3)
        hbox.addWidget(smwui.chartView)
        hbox.addWidget(scrollArea_viewParts)

        self.gb_analysis.setTitle("Analysis")
        self.gb_analysis.setLayout(hbox)
Exemplo n.º 20
0
    def update_chart(self):

        if not self.cb_targetAxis1.checkState(
        ) and not self.cb_targetAxis2.checkState(
        ) and not self.cb_targetAxis3.checkState():
            return -1

        ## draw chart
        set1 = QBarSet("X")
        set2 = QBarSet("Y")
        set3 = QBarSet("Z")
        set1.setColor(QColor(0, 0, 200, 180))
        set2.setColor(QColor(0, 200, 0, 180))
        set3.setColor(QColor(200, 100, 0, 180))

        self.categories = []
        self.set1_val = np.array([])
        self.set2_val = np.array([])
        self.set3_val = np.array([])
        for i in range(len(self.parts_dict)):
            flag_add = False
            if self.parts_dict[self.cb_targetValue1.text(
            )] == i and self.cb_targetValue1.checkState():
                flag_add = True
                self.categories.append(self.cb_targetValue1.text())
            elif self.parts_dict[self.cb_targetValue2.text(
            )] == i and self.cb_targetValue2.checkState():
                flag_add = True
                self.categories.append(self.cb_targetValue2.text())
            elif self.parts_dict[self.cb_targetValue3.text(
            )] == i and self.cb_targetValue3.checkState():
                flag_add = True
                self.categories.append(self.cb_targetValue3.text())
            elif self.parts_dict[self.cb_targetValue4.text(
            )] == i and self.cb_targetValue4.checkState():
                flag_add = True
                self.categories.append(self.cb_targetValue4.text())
            elif self.parts_dict[self.cb_targetValue5.text(
            )] == i and self.cb_targetValue5.checkState():
                flag_add = True
                self.categories.append(self.cb_targetValue5.text())
            elif self.parts_dict[self.cb_targetValue6.text(
            )] == i and self.cb_targetValue6.checkState():
                flag_add = True
                self.categories.append(self.cb_targetValue6.text())
            elif self.parts_dict[self.cb_targetValue7.text(
            )] == i and self.cb_targetValue7.checkState():
                flag_add = True
                self.categories.append(self.cb_targetValue7.text())
            elif self.parts_dict[self.cb_targetValue8.text(
            )] == i and self.cb_targetValue8.checkState():
                flag_add = True
                self.categories.append(self.cb_targetValue8.text())
            elif self.parts_dict[self.cb_targetValue9.text(
            )] == i and self.cb_targetValue9.checkState():
                flag_add = True
                self.categories.append(self.cb_targetValue9.text())

            if flag_add:
                set1 << self.ctd.distanceList[0 + 3 * i]
                set2 << self.ctd.distanceList[1 + 3 * i]
                set3 << self.ctd.distanceList[2 + 3 * i]
                self.set1_val = np.append(self.set1_val,
                                          [self.ctd.distanceList[0 + 3 * i]])
                self.set2_val = np.append(self.set2_val,
                                          [self.ctd.distanceList[1 + 3 * i]])
                self.set3_val = np.append(self.set3_val,
                                          [self.ctd.distanceList[2 + 3 * i]])

        series = QHorizontalBarSeries()
        if self.cb_targetAxis1.checkState():
            series.append(set1)
        else:
            self.set1_val = np.zeros(len(self.categories))
        if self.cb_targetAxis2.checkState():
            series.append(set2)
        else:
            self.set2_val = np.zeros(len(self.categories))
        if self.cb_targetAxis3.checkState():
            series.append(set3)
        else:
            self.set3_val = np.zeros(len(self.categories))

        axisX = QValueAxis()
        axisX.applyNiceNumbers()
        axisY = QBarCategoryAxis()
        axisY.append(self.categories)

        chart = QChart()
        chart.setTitle("Timeseries Distance")
        chart.setAnimationOptions(QChart.SeriesAnimations)
        chart.addSeries(series)
        chart.setAxisX(axisX, series)
        chart.setAxisY(axisY)

        self.chartView.setChart(chart)
        self.chartView.setRenderHint(QPainter.Antialiasing)

        self.update_parts()
Exemplo n.º 21
0
class QtHistogram(QChartView):
    def __init__(self, spec):
        super().__init__(None)
        self.spec = spec
        self.chart = QChart()
        self.chart.setTitle(self.spec.variable)
        self.chart.legend().hide()

        self.mainset = QBarSet("")
        self.mainset.append([0] * len(spec.bins))
        self.mainset.setColor(
            QColor(spec.color[0], spec.color[1], spec.color[2]))
        self.series = QBarSeries()
        self.series.append(self.mainset)

        self.setMinimumWidth(400)
        self.setMinimumHeight(230)

        self.y_ranges = [0, 1, 5, 10, 25, 50, 100, 250, 500, 1000]
        self.max_y = 1000
        self.max_y_range = 1000
        self.lookback = 30
        self.recent_max_y = deque([self.max_y_range] * self.lookback)

        font = QtGui.QFont()
        font.setPixelSize(10)

        self.axis_x = QBarCategoryAxis()
        self.axis_x.setLabelsAngle(-90)
        self.axis_x.setLabelsFont(font)

        self.axis_y = QValueAxis()
        self.axis_y.setRange(0, self.max_y)
        self.axis_x.append(map(str, spec.bins))
        self.chart.addSeries(self.series)
        self.chart.setAxisX(self.axis_x, self.series)
        self.chart.setAxisY(self.axis_y, self.series)

        self.setChart(self.chart)
        self.setRenderHint(QPainter.Antialiasing)

        self._updates_per_second = 10
        self._dataset = []

    def clear(self):
        self._dataset = []

    def update_data(self, dataset):
        data = []
        for d in dataset:
            data.append(d)
        self._dataset = data

    def redraw(self):
        if len(self._dataset) > 0:
            for i in range(len(self._dataset)):
                self.mainset.replace(i, self._dataset[i])

            # Calculate max of current values
            max_y_range = max(self._dataset)

            # Store max value
            self.recent_max_y.appendleft(max_y_range)
            if len(self.recent_max_y) > self.lookback:
                self.recent_max_y.pop()

            # Set max based on the last 30 max values,
            # to avoid flickering
            self.max_y_range = max(self.recent_max_y)

            y_range = bisect.bisect_left(self.y_ranges, self.max_y_range)
            if y_range < len(self.y_ranges):
                self.max_y = self.y_ranges[y_range]
            elif max_y_range > self.max_y:
                self.max_y += self.max_y
            elif max_y_range < self.max_y / 2:
                self.max_y = self.max_y / 2

            self.axis_y.setRange(0, self.max_y)
    def setupChartWithData(self):
        """
        Chart gets updated displaying the new data.

        Data has to be expressed on a dictionary form:
            - keys are timestamps
            - values are total balance for that timestamp
        """
        self.chart = QChart()
        self.chart.setTheme(QChart.ChartThemeDark)
        self.chart.setAnimationOptions(QChart.SeriesAnimations)
        self.chart.setBackgroundBrush(QBrush(QColor("transparent")))

        # Series
        self.barseries = QBarSeries()

        currentyear, currentmonth = datetime.today().year, datetime.today(
        ).month
        dates, amounts = [], []
        # Get 5 previous month numbers
        for _ in range(5):
            dates.append((currentmonth, currentyear))
            currentmonth -= 1
            if currentmonth == 0:
                currentmonth = 12
                currentyear -= 1
        # Get amounts for each month
        for d in dates:
            month, year = d
            amounts.append(
                dbhandler.get_total_wealth_on_month(month, year=year))

        # Iterate months and amount and insert them into the histogram appropiately
        barset = QBarSet('Total wealth')
        labelsfont = QFont()
        labelsfont.setFamily('Inter')
        labelsfont.setBold(True)
        barset.setLabelFont(labelsfont)
        barset.setColor(QColor("#D3EABD"))
        x_values = []
        for d, a in zip(reversed(dates), reversed(amounts)):
            if a > 0:
                barset.append(int(a))
                x_values.append(calendar.month_name[d[0]])

        self.barseries.append(barset)
        self.barseries.setName("Last Months")
        self.barseries.setLabelsVisible(True)
        self.barseries.setBarWidth(0.2)
        self.barseries.setLabelsPosition(QAbstractBarSeries.LabelsOutsideEnd)
        self.chart.addSeries(self.barseries)

        # Axis X (Dates)
        self.x_axis = QBarCategoryAxis()
        self.x_axis.setTitleText(self.tr('Date'))
        labelsfont = QFont()
        labelsfont.setFamily('Roboto')
        labelsfont.setLetterSpacing(QFont.AbsoluteSpacing, 1)
        labelsfont.setWeight(QFont.Light)
        labelsfont.setPointSize(9)
        self.x_axis.setLabelsFont(labelsfont)
        self.x_axis.setGridLineVisible(False)
        self.x_axis.setLineVisible(False)
        self.x_axis.setLinePenColor(QColor("#D3EABD"))
        self.x_axis.setTitleVisible(False)

        self.x_axis.append(x_values)
        self.chart.addAxis(self.x_axis, Qt.AlignBottom)

        # Axis Y (Balances)
        self.y_axis = QValueAxis()
        self.y_axis.setMax(max(amounts) * 1.3)
        self.y_axis.setMin(min(amounts) * 0.95)
        self.y_axis.hide()

        labelsfont = QFont()
        labelsfont.setPointSize(4)
        self.y_axis.setLabelsFont(labelsfont)
        self.chart.addAxis(self.y_axis, Qt.AlignLeft)

        # Attach axis to series
        self.barseries.attachAxis(self.x_axis)
        self.barseries.attachAxis(self.y_axis)

        # Legend
        self.chart.legend().hide()

        # Set up chart on ChartView
        self.setChart(self.chart)
        self.setRenderHint(QPainter.Antialiasing)
        self.setStyleSheet("border: 0px; background-color: rgba(0,0,0,0)")