def __init__(self, parent=None):
        super(TestChart, self).__init__(parent)
        self.xRange = 800
        self.sampleRate = 5
        self.counter = 0
        self.seriesList = []
        self.legend().show()

        self.axisX = QValueAxis()
        self.axisX.setRange(0, self.xRange)
        self.addAxis(self.axisX, Qt.AlignBottom)
        # self.setAxisX(self.axisX, series)

        self.axisY = QValueAxis()
        self.axisY.setRange(-1, 1)
        self.addAxis(self.axisY, Qt.AlignLeft)
        # self.setAxisY(self.axisY, series)

        for i in range(24):
            series = QLineSeries()
            series.setName("Series" + str(i))
            series.setUseOpenGL(True)
            self.addSeries(series)
            self.seriesList.append(series)
            series.attachAxis(self.axisX)
            series.attachAxis(self.axisY)
Ejemplo n.º 2
0
    def __init__(self):
        super().__init__()

        series = QLineSeries()

        for date, value in DATA:
            date_value = QDateTime(*date, 0, 0).toMSecsSinceEpoch()
            series.append(date_value, value)

        chart = QChart()
        chart.setTheme(QChart.ChartThemeDark)
        chart.setTitle("Line Chart with Date Example")
        chart.setAnimationOptions(QChart.SeriesAnimations)
        chart.addSeries(series)
        chart.legend().hide()

        axisX = QDateTimeAxis()
        axisX.setFormat("dd/MM/yyyy")
        axisX.setTitleText('Date')
        chart.addAxis(axisX, Qt.AlignBottom)
        series.attachAxis(axisX)

        axisY = QValueAxis()
        axisY.setTitleText('Value')
        chart.addAxis(axisY, Qt.AlignLeft)
        series.attachAxis(axisY)

        chart_view = QChartView()
        chart_view.setChart(chart)
        chart_view.setRenderHint(QPainter.Antialiasing)

        self.setCentralWidget(chart_view)
Ejemplo n.º 3
0
class ChartWidget(QWidget):
    def __init__(self, parent=None, ticker="BTC"):
        super().__init__(parent)
        uic.loadUi("resource/chart.ui", self)
        self.ticker = ticker
        self.viewLimit = 128

        self.priceData = QLineSeries()
        self.priceChart = QChart()
        self.priceChart.addSeries(self.priceData)
        self.priceChart.legend().hide()

        # ----------------- 추 가 ------------------
        axisX = QDateTimeAxis()
        axisX.setFormat("hh:mm:ss")
        axisX.setTickCount(4)
        dt = QDateTime.currentDateTime()
        axisX.setRange(dt, dt.addSecs(self.viewLimit))
        axisY = QValueAxis()
        axisY.setVisible(False)

        self.priceChart.addAxis(axisX, Qt.AlignBottom)
        self.priceChart.addAxis(axisY, Qt.AlignRight)
        self.priceData.attachAxis(axisX)
        self.priceData.attachAxis(axisY)
        self.priceChart.layout().setContentsMargins(0, 0, 0, 0)
        # ------------------------------------------

        self.priceView.setChart(self.priceChart)
        self.priceView.setRenderHints(QPainter.Antialiasing)
 def setSubplots(self, count: int):
     for _ in range(count):
         series = QLineSeries()
         self.chart.addSeries(series)
         series.attachAxis(self.xAxis)
         series.attachAxis(self.yAxis)
         self.seriesList.append(series)
Ejemplo n.º 5
0
   def __createChart(self):
      self.__chart = QChart()
      self.__chart.setTitle("简单函数曲线")
      self.ui.chartView.setChart(self.__chart)
      self.ui.chartView.setRenderHint(QPainter.Antialiasing)

      series0 =  QLineSeries()
      series0.setName("Sin曲线")
      series1 =  QLineSeries()
      series1.setName("Cos曲线")
      self.__curSeries=series0   #当前序列

      pen=QPen(Qt.red)
      pen.setStyle(Qt.DotLine)   #SolidLine, DashLine, DotLine, DashDotLine
      pen.setWidth(2)
      series0.setPen(pen)        #序列的线条设置

      pen.setStyle(Qt.SolidLine) #SolidLine, DashLine, DotLine, DashDotLine
      pen.setColor(Qt.blue)
      series1.setPen(pen)        #序列的线条设置

      self.__chart.addSeries(series0)
      self.__chart.addSeries(series1)

      axisX = QValueAxis()
      self.__curAxis=axisX       #当前坐标轴
      axisX.setRange(0, 10)      #设置坐标轴范围
      axisX.setLabelFormat("%.1f")  #标签格式
      axisX.setTickCount(11)        #主分隔个数
      axisX.setMinorTickCount(4)
      axisX.setTitleText("time(secs)")  #标题
      axisX.setGridLineVisible(True)
      axisX.setMinorGridLineVisible(False)

      axisY = QValueAxis()
      axisY.setRange(-2, 2)
      axisY.setLabelFormat("%.2f")     #标签格式
      axisY.setTickCount(5)
      axisY.setMinorTickCount(4)
      axisY.setTitleText("value")
      axisY.setGridLineVisible(True)
      axisY.setMinorGridLineVisible(False)

   ##      self.__chart.setAxisX(axisX, series0) #添加X坐标轴
   ##      self.__chart.setAxisX(axisX, series1) #添加X坐标轴
   ##      self.__chart.setAxisY(axisY, series0) #添加Y坐标轴
   ##      self.__chart.setAxisY(axisY, series1) #添加Y坐标轴

   ##另一种实现设置坐标轴的方法
      self.__chart.addAxis(axisX,Qt.AlignBottom) #坐标轴添加到图表,并指定方向
      self.__chart.addAxis(axisY,Qt.AlignLeft)

      series0.attachAxis(axisX)  #序列 series0 附加坐标轴
      series0.attachAxis(axisY)

      series1.attachAxis(axisX)  #序列 series1 附加坐标轴
      series1.attachAxis(axisY)
Ejemplo n.º 6
0
class ChartWidget(QWidget):
    def __init__(self, parent=None, ticker="BTC"):
        super().__init__(parent)
        uic.loadUi("chart.ui", self)
        self.ticker = ticker
        self.viewLimit = 128

        self.priceData = QLineSeries()
        self.priceChart = QChart()
        self.priceChart.addSeries(self.priceData)
        self.priceChart.legend().hide()

        axisX = QDateTimeAxis()
        axisX.setFormat("hh:mm:ss")
        axisX.setTickCount(4)
        dt = QDateTime.currentDateTime()
        axisX.setRange(dt, dt.addSecs(self.viewLimit))
        axisY = QValueAxis()
        axisY.setVisible(False)

        self.priceChart.addAxis(axisX, Qt.AlignBottom)
        self.priceChart.addAxis(axisY, Qt.AlignRight)
        self.priceData.attachAxis(axisX)
        self.priceData.attachAxis(axisY)
        self.priceChart.layout().setContentsMargins(0, 0, 0, 0)

        self.priceView.setChart(self.priceChart)
        self.priceView.setRenderHints(QPainter.Antialiasing)

        # ----------------- 추 가 ------------------
        self.pw = PriceWorker(ticker)
        self.pw.dataSent.connect(self.appendData)
        self.pw.start()
        # ------------------------------------------

    def appendData(self, currPirce):
        if len(self.priceData) == self.viewLimit:
            self.priceData.remove(0)
        dt = QDateTime.currentDateTime()
        self.priceData.append(dt.toMSecsSinceEpoch(), currPirce)
        self.__updateAxis()

    def __updateAxis(self):
        pvs = self.priceData.pointsVector()
        dtStart = QDateTime.fromMSecsSinceEpoch(int(pvs[0].x()))
        if len(self.priceData) == self.viewLimit:
            dtLast = QDateTime.fromMSecsSinceEpoch(int(pvs[-1].x()))
        else:
            dtLast = dtStart.addSecs(self.viewLimit)
        ax = self.priceChart.axisX()
        ax.setRange(dtStart, dtLast)

        ay = self.priceChart.axisY()
        dataY = [v.y() for v in pvs]
        ay.setRange(min(dataY), max(dataY))
Ejemplo n.º 7
0
class CharPlotWidget(QChartView):

    def __init__(self, parent=None):
        super().__init__(parent=parent)

        self.setRenderHint(QPainter.Antialiasing)

        self._chart = self.chart()
        self._axis_x = QValueAxis()
        self._axis_y = QValueAxis()

        self.series = QLineSeries(self)

        self._chart.addSeries(self.series)
        self._chart.addAxis(self._axis_x, Qt.AlignBottom)
        self._chart.addAxis(self._axis_y, Qt.AlignLeft)

        self.series.attachAxis(self._axis_x)
        self.series.attachAxis(self._axis_y)

        self._axis_x.setTickCount(5)
        self._axis_x.setRange(0, 10)

        self._axis_y.setTickCount(5)
        self._axis_y.setRange(0, 10)

        self._chart.legend().hide()

    def plot(self, xs, ys):
        self.series.replace([QPointF(x, y) for x, y in zip(xs, ys)])

    @property
    def axes_titles(self):
        return self._axis_x.titleText(), self._axis_y.titleText()

    @axes_titles.setter
    def axes_titles(self, value):
        x, y = value
        self._axis_x.setTitleText(x)
        self._axis_y.setTitleText(y)

    @property
    def title(self):
        return self._chart.title()

    @title.setter
    def title(self, value):
        self._chart.setTitle(value)

    @property
    def legend(self):
        return self._chart.legend()
Ejemplo n.º 8
0
class ChartView(QChartView):
    def __init__(self):
        QChartView.__init__(self)
        #self.resize(300, 300)
        self.setRenderHint(QPainter.Antialiasing)  # 抗锯齿
        self.chart = QChart()
        self.seriesAcc = QLineSeries()
        self.seriesAcc.setName(CONF.leftUpNames[0])
        self.chart.addSeries(self.seriesAcc)
        #声明并初始化X轴,Y轴
        self.dtaxisX = QValueAxis()
        self.vlaxisY = QValueAxis()
        #设置坐标轴显示范围
        self.dtaxisX.setMin(0)
        #self.dtaxisX.setMax(100)
        self.vlaxisY.setMin(0)
        #self.vlaxisY.setMax(100)
        self.dtaxisX.setTickCount(3)
        self.vlaxisY.setTickCount(3)
        #设置坐标轴名称
        self.dtaxisX.setTitleText(CONF.leftUpNames[1])
        self.vlaxisY.setTitleText(CONF.leftUpNames[2])
        #设置网格不显示
        self.vlaxisY.setGridLineVisible(False)
        #把坐标轴添加到chart中
        self.chart.addAxis(self.dtaxisX, Qt.AlignBottom)
        self.chart.addAxis(self.vlaxisY, Qt.AlignLeft)

        self.seriesAcc.attachAxis(self.dtaxisX)
        self.seriesAcc.attachAxis(self.vlaxisY)

        self.initUI()

    def initUI(self):
        self.backend = BackendThread()
        self.backend.update_line.connect(self.handleLine)
        self.backend.start()

    def handleLine(self, data):
        if data[0] == 0:
            self.seriesAcc.clear()
        else:
            self.dtaxisX.setMax(data[0])
            self.vlaxisY.setMax(data[0])
            self.seriesAcc.clear()
            self.seriesAcc.append(0, 0)
            self.seriesAcc.append(data[0], data[1])

        self.setChart(self.chart)
Ejemplo n.º 9
0
    def setupChart(self):
        """Set up the GUI's graph line series type, chart instance, chart axes, 
        and chart view widget."""
        # Collect x and y data values from the CSV file
        x_values, y_values = self.loadCSVFile()

        # Create chart object
        chart = QChart()
        chart.setTitle(
            "Public Social Spending as a Share of GDP for Sweden, 1880 to 2016"
        )
        chart.setAnimationOptions(QChart.SeriesAnimations)
        chart.legend().hide()  # Hide the chart's legend

        line_series = QLineSeries()  # Using line charts for this example
        #line_series.setPointLabelsVisible(True)
        #line_series.setPen(QColor(Qt.blue))

        # Loop through corresponding x and y values and add them to the line chart
        for value in range(0, self.row_count - 1):
            line_series.append(x_values[value], y_values[value])
        chart.addSeries(line_series)  # Add line series to chart instance

        # Specify parameters for the x and y axes
        axis_x = QValueAxis()
        axis_x.setLabelFormat("%i")
        axis_x.setTickCount(10)
        axis_x.setRange(1880, 2016)
        chart.addAxis(axis_x, Qt.AlignBottom)
        line_series.attachAxis(axis_x)

        axis_y = QValueAxis()
        axis_y.setLabelFormat("%i" + "%")
        axis_y.setRange(0, 40)
        chart.addAxis(axis_y, Qt.AlignLeft)
        line_series.attachAxis(axis_y)

        # Create QChartView object for displaying the chart
        chart_view = QChartView(chart)
        chart_view.setRenderHint(QPainter.Antialiasing)

        # Create layout and set the layout for the window
        v_box = QVBoxLayout()
        v_box.addWidget(chart_view)
        self.setLayout(v_box)
Ejemplo n.º 10
0
class PeersCountGraphView(BaseTimedGraph):
    peersCountFetched = AsyncSignal(int)

    def __init__(self, parent=None):
        super(PeersCountGraphView, self).__init__(parent=parent)

        self.setObjectName('PeersCountGraph')
        self.peersCountFetched.connectTo(self.onPeersCount)
        self.axisY.setTitleText(iPeers())

        pen = QPen(QColor('#60cccf'))
        pen.setWidth(2)

        self.seriesPeers = QLineSeries()
        self.seriesPeers.setName('Peers')
        self.seriesPeers.setPen(pen)
        self.chart.addSeries(self.seriesPeers)
        self.seriesPeers.attachAxis(self.axisX)
        self.seriesPeers.attachAxis(self.axisY)

        self.setChart(self.chart)

    async def onPeersCount(self, count):
        dtNow = QDateTime.currentDateTime()
        dtMsecs = dtNow.toMSecsSinceEpoch()

        delta = 120 * 1000
        if not self.seriesPurgedT or (dtMsecs - self.seriesPurgedT) > delta:
            self.removeOldSeries(self.seriesPeers, dtMsecs - delta)
            self.seriesPurgedT = dtMsecs

        peersVector = self.seriesPeers.pointsVector()
        values = [p.y() for p in peersVector]

        if values:
            self.axisY.setMax(max(values) + 10)
            self.axisY.setMin(min(values) - 10)

        dateMin = QDateTime.fromMSecsSinceEpoch(dtMsecs - (30 * 1000))
        dateMax = QDateTime.fromMSecsSinceEpoch(dtMsecs + 2000)

        self.seriesPeers.append(dtMsecs, count)
        self.axisX.setRange(dateMin, dateMax)
Ejemplo n.º 11
0
   def do_redrawWave(self):
      self.chart.removeAllSeries()  # 删除所有序列
      pen=QPen(self.__colorLine)    # 曲线颜色
      pen.setWidth(2)
      seriesWave = QLineSeries() 
      seriesWave.setUseOpenGL(True) 
      seriesWave.setPen(pen)

      vx=0
      intv=0.001  #1000Hz采样
      pointCount=len(self.__vectData)
      for i in range(pointCount):
         value=self.__vectData[i]
         seriesWave.append(vx,value)
         vx =vx+ intv
      self.__axisX.setRange(0,vx)

      self.chart.addSeries(seriesWave)
      seriesWave.attachAxis(self.__axisX)
      seriesWave.attachAxis(self.__axisY)
Ejemplo n.º 12
0
    def _fill_chart(self, items: List[Run]):
        series = QLineSeries()
        series.setPointsVisible(True)
        series.setPointLabelsVisible(True)
        series.setPointLabelsFormat("@yPoint")
        series.hovered.connect(self.chart_view.show_series_tooltip)

        self.timestamp_by_run.clear()

        for run in items:
            date_value = calendar.timegm(run.date.timetuple()) * 1000
            total_issues = run.get_total_issues()
            series.append(date_value, total_issues)

            self.timestamp_by_run[date_value] = run

        chart = QChart()
        chart.setTheme(QChart.ChartThemeDark)
        chart.setAnimationOptions(QChart.SeriesAnimations)
        chart.addSeries(series)
        chart.legend().hide()

        # No margin
        chart.layout().setContentsMargins(0, 0, 0, 0)
        chart.setBackgroundRoundness(0)

        axisX = QDateTimeAxis()
        axisX.setFormat("dd/MM/yyyy")
        axisX.setTitleText('Date')
        chart.addAxis(axisX, Qt.AlignBottom)
        series.attachAxis(axisX)

        axisY = QValueAxis()
        axisY.setLabelFormat('%d')
        axisY.setTitleText('Total issues')
        chart.addAxis(axisY, Qt.AlignLeft)
        series.attachAxis(axisY)

        self.chart_view.clear_all_tooltips()
        self.chart_view.setChart(chart)
Ejemplo n.º 13
0
    def __init__(self):
        super().__init__()
        # window size
        self.setMinimumSize(600, 400)

        df = pyupbit.get_ohlcv("KRW-BTC")

        # data
        series = QLineSeries()
        for index in df.index:
            close = df.loc[index, 'close']
            dt = index.timestamp() * 1000       # msecs
            series.append(dt, close)

        # chart object
        chart = QChart()
        chart.legend().hide()
        chart.addSeries(series)         # data feeding

        # axis
        axis_x = QDateTimeAxis()
        axis_x.setFormat("yyyy-MM-dd")
        chart.addAxis(axis_x, Qt.AlignBottom)
        series.attachAxis(axis_x)

        axis_y = QValueAxis()
        axis_y.setLabelFormat("%i")
        chart.addAxis(axis_y, Qt.AlignLeft)
        series.attachAxis(axis_y)

        # margin
        chart.layout().setContentsMargins(0, 0, 0, 0)


        # displaying chart
        chart_view = QChartView(chart)
        chart_view.setRenderHint(QPainter.Antialiasing)
        self.setCentralWidget(chart_view)
Ejemplo n.º 14
0
    def __drawBode(self):
        self.chart.removeAllSeries()  #删除所有序列
        ## 创建序列
        pen = QPen(Qt.red)
        pen.setWidth(2)

        seriesMag = QLineSeries()  #幅频曲线序列
        seriesMag.setName("幅频曲线")
        seriesMag.setPen(pen)
        seriesMag.setPointsVisible(False)
        seriesMag.hovered.connect(self.do_seriesMag_hovered)

        seriesPhase = QLineSeries()  #相频曲线序列
        pen.setColor(Qt.blue)
        seriesPhase.setName("相频曲线")
        seriesPhase.setPen(pen)
        seriesPhase.setPointsVisible(True)
        seriesPhase.hovered.connect(self.do_seriesPhase_hovered)

        ## 为序列添加数据点
        count = len(self.__vectW)  #数据点数
        for i in range(count):
            seriesMag.append(self.__vectW[i], self.__vectMag[i])
            seriesPhase.append(self.__vectW[i], self.__VectPhase[i])

    ##设置坐标轴范围
        minMag = min(self.__vectMag)
        maxMag = max(self.__vectMag)
        minPh = min(self.__VectPhase)
        maxPh = max(self.__VectPhase)
        self.__axisMag.setRange(minMag, maxMag)
        self.__axisPhase.setRange(minPh, maxPh)

        ##序列添加到chart,并指定坐标轴
        self.chart.addSeries(seriesMag)
        seriesMag.attachAxis(self.__axisFreq)
        seriesMag.attachAxis(self.__axisMag)

        self.chart.addSeries(seriesPhase)
        seriesPhase.attachAxis(self.__axisFreq)
        seriesPhase.attachAxis(self.__axisPhase)

        for marker in self.chart.legend().markers():  #QLegendMarker类型列表
            marker.clicked.connect(self.do_LegendMarkerClicked)
Ejemplo n.º 15
0
class AmzHistoryChart(QWidget):
    """A chart that graphs the history of an AmazonListing's sales rank, price, and number of offers."""

    def __init__(self, parent=None):
        super(AmzHistoryChart, self).__init__(parent=parent)

        self.dbsession = Session()
        self.context_menu_actions = []
        self._avg_pointspan = 0
        self._max_points = 100
        self.source = None
        self.history = None

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        # Set up the chart
        self.chart_view = QChartView(self)
        self.chart_view.setRenderHint(QPainter.Antialiasing)
        self.chart_view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.chart_view.customContextMenuRequested.connect(self.context_menu)

        self.chart = QChart()
        self.chart.legend().hide()
        self.chart.setFlags(QGraphicsItem.ItemIsFocusable | QGraphicsItem.ItemIsSelectable)
        self.chart.installEventFilter(self)
        self.chart_view.setChart(self.chart)

        self.layout().addWidget(self.chart_view)

        # Create the axes
        rcolor = QColor(50, 130, 220)
        pcolor = QColor(0, 200, 0)
        ocolor = QColor(255, 175, 0)

        self.timeAxis = QDateTimeAxis()
        self.timeAxis.setFormat('M/dd hh:mm')
        self.timeAxis.setTitleText('Date/Time')
        self.chart.addAxis(self.timeAxis, Qt.AlignBottom)

        self.timeAxis.minChanged.connect(self.on_timeaxis_min_changed)

        self.rankAxis = QValueAxis()
        self.rankAxis.setLabelFormat('%\'i')
        self.rankAxis.setTitleText('Sales Rank')
        self.rankAxis.setLinePenColor(rcolor)
        self.rankAxis.setLabelsColor(rcolor)
        self.chart.addAxis(self.rankAxis, Qt.AlignLeft)

        self.priceAxis = QValueAxis()
        self.priceAxis.setLabelFormat('$%.2f')
        self.priceAxis.setTitleText('Price')
        self.priceAxis.setLinePenColor(pcolor)
        self.priceAxis.setLabelsColor(pcolor)
        self.chart.addAxis(self.priceAxis, Qt.AlignRight)

        # Create the series
        self.rankLine = QLineSeries()
        self.chart.addSeries(self.rankLine)
        self.rankLine.attachAxis(self.timeAxis)
        self.rankLine.attachAxis(self.rankAxis)
        self.rankLine.setColor(rcolor)

        self.priceLine = QLineSeries()
        self.chart.addSeries(self.priceLine)
        self.priceLine.attachAxis(self.timeAxis)
        self.priceLine.attachAxis(self.priceAxis)
        self.priceLine.setColor(pcolor)

        self.salesPoints = QScatterSeries()
        self.chart.addSeries(self.salesPoints)
        self.salesPoints.attachAxis(self.timeAxis)
        self.salesPoints.attachAxis(self.rankAxis)
        self.salesPoints.setColor(ocolor)

    def add_context_action(self, action):
        """Add an action to the chart's context menu."""
        self.context_menu_actions.append(action)

    def add_context_actions(self, actions):
        """Adds all action in an iterable."""
        self.context_menu_actions.extend(actions)

    def remove_context_action(self, action):
        """Removes an action from the chart's context menu."""
        self.context_menu_actions.remove(action)

    def context_menu(self, point):
        """Show a context menu on the chart."""
        menu = QMenu(self)
        menu.addActions(self.context_menu_actions)

        point = self.chart_view.viewport().mapToGlobal(point)
        menu.popup(point)

    def set_source(self, source):
        """Set the source listing for the graph."""
        self.source = source

        # Update the chart
        self.rankLine.clear()
        self.priceLine.clear()
        self.salesPoints.clear()
        self.history = None

        start_date = datetime.utcnow() - timedelta(days=5)
        self.load_history_from(start_date)

        self.reset_axes()

    def load_history_from(self, start_date=datetime.utcfromtimestamp(0)):
        """Load history data from start-present."""
        if not self.source:
            self._avg_pointspan = 0
            return

        # Get the earliest point already in the chart
        points = self.rankLine.pointsVector()

        if points:
            # The chart is drawn right-to-left, so the last point is the earliest point
            earliest_msecs = points[-1].x()
            earliest = datetime.fromtimestamp(earliest_msecs / 1000, timezone.utc)

            if earliest <= start_date:
                return

        else:
            earliest = datetime.now(timezone.utc)

        # Get the product history stats if we don't already have them
        if self.history is None:
            self.history = dbhelpers.ProductHistoryStats(self.dbsession, self.source.id)

        # Start adding points to the chart
        last_row = None
        for row in self.dbsession.query(AmzProductHistory).\
                                  filter(AmzProductHistory.amz_listing_id == self.source.id,
                                         AmzProductHistory.timestamp > start_date.replace(tzinfo=None),
                                         AmzProductHistory.timestamp < earliest.replace(tzinfo=None)).\
                                  order_by(AmzProductHistory.timestamp.desc()):

            # SqlAlchemy returns naive timestamps
            time = row.timestamp.replace(tzinfo=timezone.utc).timestamp() * 1000

            self.rankLine.append(time, row.salesrank or 0)
            self.priceLine.append(time, row.price or 0)

            if last_row:
                # It's possible for salesrank to be None
                try:
                    slope = (last_row.salesrank - row.salesrank) / (last_row.timestamp.timestamp() - row.timestamp.timestamp())
                    if slope < -0.3:
                        self.salesPoints.append(last_row.timestamp.replace(tzinfo=timezone.utc).timestamp() * 1000,
                                                last_row.salesrank)
                except (TypeError, AttributeError):
                    pass

            last_row = row

        # Calculate the average span between points
        spans = 0
        for p1, p2 in itertools.zip_longest(itertools.islice(points, 0, None, 2), itertools.islice(points, 1, None, 2)):
            if p1 and p2: spans += abs(p1.x() - p2.x())

        self._avg_pointspan = spans // 2

    def on_timeaxis_min_changed(self, min):
        """Respond to a change in the time axis' minimum value."""
        # toTime_t() converts to UTC automatically
        utc_min = datetime.fromtimestamp(min.toTime_t(), timezone.utc)
        self.load_history_from(start_date=utc_min - timedelta(days=1))

    def reset_axes(self):
        """Resets the chart axes."""
        r = self.rankLine.pointsVector()
        p = self.priceLine.pointsVector()

        # If there is only one data point, set the min and max to the day before and the day after
        if len(r) == 1:
            tmin = QDateTime.fromMSecsSinceEpoch(r[0].x(), Qt.LocalTime).addDays(-1)
            tmax = QDateTime.fromMSecsSinceEpoch(r[0].x(), Qt.LocalTime).addDays(+1)
        else:
            tmin = min(r, key=lambda pt: pt.x(), default=QPointF(QDateTime.currentDateTime().addDays(-1).toMSecsSinceEpoch(), 0)).x()
            tmax = max(r, key=lambda pt: pt.x(), default=QPointF(QDateTime.currentDateTime().addDays(+1).toMSecsSinceEpoch(), 0)).x()
            tmin = QDateTime.fromMSecsSinceEpoch(tmin, Qt.LocalTime)
            tmax = QDateTime.fromMSecsSinceEpoch(tmax, Qt.LocalTime)

        self.timeAxis.setMin(tmin)
        self.timeAxis.setMax(tmax)

        # Find the min and max values of the series
        min_point = lambda pts: min(pts, key=lambda pt: pt.y(), default=QPointF(0, 0))
        max_point = lambda pts: max(pts, key=lambda pt: pt.y(), default=QPointF(0, 0))

        rmin = min_point(r)
        rmax = max_point(r)
        pmin = min_point(p)
        pmax = max_point(p)

        # Scale the mins and maxes to 'friendly' values
        scalemin = lambda v, step: ((v - step / 2) // step) * step
        scalemax = lambda v, step: ((v + step / 2) // step + 1) * step

        # The the axis bounds

        rmin = max(scalemin(rmin.y(), 1000), 0)
        rmax = scalemax(rmax.y(), 1000)
        pmin = max(scalemin(pmin.y(), 5), 0)
        pmax = scalemax(pmax.y(), 5)

        self.rankAxis.setMin(rmin)
        self.rankAxis.setMax(rmax)
        self.priceAxis.setMin(pmin)
        self.priceAxis.setMax(pmax)

    def eventFilter(self, watched, event):
        """Intercept and handle mouse events."""
        if event.type() == QEvent.GraphicsSceneWheel and event.orientation() == Qt.Vertical:
            factor = 0.95 if event.delta() < 0 else 1.05
            self.chart.zoom(factor)
            return True

        if event.type() == QEvent.GraphicsSceneMouseDoubleClick:
            self.chart.zoomReset()
            self.reset_axes()
            return True

        if event.type() == QEvent.GraphicsSceneMouseMove:
            delta = event.pos() - event.lastPos()
            self.chart.scroll(-delta.x(), delta.y())
            return True

        return False
Ejemplo n.º 16
0
    def setupChart(self):
        """Set up the GUI's graph series type, chart instance, chart axes, 
        and chart view widget."""
        random.seed(50) # Create seed for random numbers

        # Create the model instance and set the headers
        self.model = QStandardItemModel()
        self.model.setColumnCount(3)
        self.model.setHorizontalHeaderLabels(["Year", "Social Exp. %GDP", "Country"])

        # Collect x and y data values and labels from the CSV file
        xy_data_and_labels = self.loadCSVFile()

        # Create the individual lists for x, y and labels values
        x_values, y_values, labels = [], [], []
        # Append items to the corresponding lists
        for item in range(len(xy_data_and_labels)):
            x_values.append(xy_data_and_labels[item][0])
            y_values.append(xy_data_and_labels[item][1])
            labels.append(xy_data_and_labels[item][2])

        # Remove all duplicates from the labels list using list comprehension. 
        # This list will be used to create the labels in the chart's legend.
        set_of_labels = []
        [set_of_labels.append(x) for x in labels if x not in set_of_labels]  
    
        # Create chart object
        self.chart = QChart()
        self.chart.setTitle("Public Social Spending as a Share of GDP, 1880 to 2016")
        self.chart.legend().hide() # Hide legend at the start

        # Specify parameters for the x and y axes
        self.axis_x = QValueAxis()
        self.axis_x.setLabelFormat("%i")
        self.axis_x.setTickCount(10)
        self.axis_x.setRange(1880, 2016)
        self.chart.addAxis(self.axis_x, Qt.AlignBottom)

        self.axis_y = QValueAxis()
        self.axis_y.setLabelFormat("%i" + "%")
        self.axis_y.setRange(0, 40)
        self.chart.addAxis(self.axis_y, Qt.AlignLeft)

        # Create a Python dict to associate the labels with the individual line series
        series_dict = {}

        for label in set_of_labels:
            # Create labels from data and add them to a Python dictionary
            series_label = 'series_{}'.format(label)
            series_dict[series_label] = label # Create label value for each line series

        # For each of the keys in the dict, create a line series
        for keys in series_dict.keys():
            # Use get() to access the corresponding value for a key
            label = series_dict.get(keys)

            # Create line series instance and set its name and color values
            line_series = QLineSeries()
            line_series.setName(label)
            line_series.setColor(QColor(random.randint(10, 254), random.randint(10, 254), random.randint(10, 254)))

            # Append x and y coordinates to the series
            for value in range(len(xy_data_and_labels)):
                if line_series.name() == xy_data_and_labels[value][2]:
                    line_series.append(x_values[value], y_values[value])

                    # Create and add items to the model (for displaying the table)
                    items = [QStandardItem(str(item)) for item in xy_data_and_labels[value]]
                    color = line_series.pen().color()
                    for item in items:
                        item.setBackground(color)
                    self.model.insertRow(value, items)

            self.chart.addSeries(line_series)
            line_series.attachAxis(self.axis_x)
            line_series.attachAxis(self.axis_y)   

        # Create QChartView object for displaying the chart 
        self.chart_view = ChartView(self.chart)
        self.setCentralWidget(self.chart_view)
Ejemplo n.º 17
0
class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # thread
        self.worker = Worker()
        self.worker.price.connect(self.get_price)
        self.worker.start()

        # window size
        self.setMinimumSize(600, 400)

        # data
        self.series = QLineSeries()

        # chart object
        self.chart = QChart()
        self.chart.legend().hide()
        self.chart.addSeries(self.series)  # data feeding

        # axis
        axis_x = QDateTimeAxis()
        axis_x.setFormat("hh:mm:ss")

        dt = QDateTime.currentDateTime()
        axis_x.setRange(dt, dt.addSecs(128))

        self.chart.addAxis(axis_x, Qt.AlignBottom)
        self.series.attachAxis(axis_x)

        axis_y = QValueAxis()
        axis_y.setLabelFormat("%i")
        self.chart.addAxis(axis_y, Qt.AlignLeft)
        self.series.attachAxis(axis_y)

        # margin
        self.chart.layout().setContentsMargins(0, 0, 0, 0)

        # displaying chart
        chart_view = QChartView(self.chart)
        chart_view.setRenderHint(QPainter.Antialiasing)
        self.setCentralWidget(chart_view)

    @pyqtSlot(float)
    def get_price(self, cur_price):
        if len(self.series) == 128:
            self.series.remove(0)  # delete first data

        # append current price
        dt = QDateTime.currentDateTime()
        ts = dt.toMSecsSinceEpoch()
        self.series.append(ts, cur_price)
        print(ts, cur_price)

        # update asis
        data = self.series.pointsVector()
        first_ts = data[0].x()
        last_ts = data[-1].x()
        first_dt = QDateTime.fromMSecsSinceEpoch(first_ts)
        last_dt = QDateTime.fromMSecsSinceEpoch(last_ts)

        axis_x = self.chart.axisX()
        axis_x.setRange(first_dt, last_dt)

        axis_y = self.chart.axisY()
        axis_y.setRange(70000000, 71000000)
Ejemplo n.º 18
0
class BandwidthGraphView(BaseTimedGraph):
    bwStatsFetched = AsyncSignal(dict)

    def __init__(self, parent=None):
        super(BandwidthGraphView, self).__init__(parent=parent)

        self.setObjectName('BandwidthGraph')
        self.chart.setTitle(iBandwidthUsage())
        self.axisY.setTitleText(iRateKbPerSecond())

        self.bwStatsFetched.connectTo(self.onBwStats)

        penIn = QPen(QColor('red'))
        penIn.setWidth(2)
        penOut = QPen(QColor('blue'))
        penOut.setWidth(2)

        self.seriesKbIn = QLineSeries()
        self.seriesKbIn.setName(iRateInput())
        self.seriesKbIn.setPen(penIn)
        self.chart.addSeries(self.seriesKbIn)
        self.seriesKbIn.attachAxis(self.axisX)
        self.seriesKbIn.attachAxis(self.axisY)

        self.seriesKbOut = QLineSeries()
        self.seriesKbOut.setName(iRateOutput())
        self.seriesKbOut.setPen(penOut)
        self.chart.addSeries(self.seriesKbOut)
        self.seriesKbOut.attachAxis(self.axisX)
        self.seriesKbOut.attachAxis(self.axisY)

        self.setChart(self.chart)

    async def onBwStats(self, stats):
        dtNow = QDateTime.currentDateTime()
        dtMsecs = dtNow.toMSecsSinceEpoch()

        delta = 120 * 1000
        if not self.seriesPurgedT or (dtMsecs - self.seriesPurgedT) > delta:
            self.removeOldSeries(self.seriesKbIn, dtMsecs - delta)
            self.removeOldSeries(self.seriesKbOut, dtMsecs - delta)
            self.seriesPurgedT = dtMsecs

        rateIn = stats.get('RateIn', 0)
        rateOut = stats.get('RateOut', 0)
        rateInKb = int(rateIn / 1024)
        rateOutKb = int(rateOut / 1024)

        inVector = self.seriesKbIn.pointsVector()
        outVector = self.seriesKbIn.pointsVector()

        inValues = [p.y() for p in inVector]
        outValues = [p.y() for p in outVector]

        if inValues or outValues:
            self.axisY.setMax(max(max(inValues), max(outValues)))

        dateMin = QDateTime.fromMSecsSinceEpoch(dtMsecs - (30 * 1000))
        dateMax = QDateTime.fromMSecsSinceEpoch(dtMsecs + 2000)

        self.seriesKbIn.append(dtMsecs, rateInKb)
        self.seriesKbOut.append(dtMsecs, rateOutKb)
        self.axisX.setRange(dateMin, dateMax)
Ejemplo n.º 19
0
def lines_stacked(name, table_df, x_bottom_cols, y_left_cols, y_right_cols,
                  legend_labels, tick_count):
    """
    折线堆叠图
    :param name: 图表名称
    :param table_df: 用于画图的pandas DataFrame对象
    :param x_bottom_cols:  下轴列索引列表
    :param y_left_cols: 左轴列索引列表
    :param y_right_cols: 右轴列索引列表
    :param legend_labels: 图例名称标签列表
    :param tick_count: 横轴刻度标签数
    :return: QChart实例
    """
    """ 过滤轴 """
    for y_left_col in y_left_cols:
        if is_datetime64_any_dtype(table_df[y_left_col]):  # 如果是时间轴
            y_left_cols.remove(y_left_col)
    for y_right_col in y_right_cols:
        if is_datetime64_any_dtype(table_df[y_right_col]):  # 如果是时间轴
            y_right_cols.remove(y_right_col)
    # 将x轴转为字符串
    x_bottom = x_bottom_cols[0]  # x轴列
    if is_datetime64_any_dtype(table_df[x_bottom]):  # 如果x轴是时间轴
        table_df[x_bottom] = table_df[x_bottom].apply(
            lambda x: x.strftime('%Y-%m-%d'))
    else:  # x轴非时间轴
        table_df[x_bottom] = table_df[x_bottom].apply(lambda x: str(x))
    font = QFont()  # 轴文字风格
    font.setPointSize(7)  # 轴标签文字大小
    chart = QChart()  # 图表实例
    chart.layout().setContentsMargins(0, 0, 0, 0)  # chart的外边距
    chart.setMargins(QMargins(15, 5, 15, 0))  # chart内边距
    chart.setTitle(name)  # chart名称
    """ x轴 """
    axis_x_bottom = QCategoryAxis(
        chart, labelsPosition=QCategoryAxis.AxisLabelsPositionOnValue)
    axis_x_bottom.setLabelsAngle(-90)  # 逆时针旋转90度
    axis_x_bottom.setLabelsFont(font)  # 设置字体样式
    axis_x_bottom.setGridLineVisible(False)  # 竖向连接线不可见
    chart.addAxis(axis_x_bottom, Qt.AlignBottom)  # 加入坐标x轴
    has_x_labels = False  # 收集x轴刻度的开关
    chart.x_labels = list()  # 绑定chart一个x轴的刻度列表
    """ 左Y轴 """
    axis_y_left = QValueAxis()
    axis_y_left.setLabelsFont(font)
    axis_y_left.setLabelFormat('%i')
    chart.addAxis(axis_y_left, Qt.AlignLeft)  # 图表加入左轴
    """ 右Y轴 """
    axis_y_right = QValueAxis()
    axis_y_right.setLabelsFont(font)
    axis_y_right.setLabelFormat('%.2f')
    chart.addAxis(axis_y_right, Qt.AlignRight)
    # 记录各轴的最值
    x_bottom_min, x_bottom_max = 0, table_df.shape[0]
    y_left_min, y_left_max = 0, 0
    y_right_min, y_right_max = 0, 0
    """ 根据左轴画折线 """
    for y_left_col in y_left_cols:  # 根据左轴画折线
        # 计算做轴的最值用于设置范围
        table_df[y_left_col] = table_df[y_left_col].apply(
            covert_float)  # y轴列转为浮点数值
        # 获取最值
        y_min, y_max = table_df[y_left_col].min(), table_df[y_left_col].max()
        if y_min < y_left_min:
            y_left_min = y_min
        if y_max > y_left_max:
            y_left_max = y_max
        # 取得图线的源数据作折线图
        left_line_data = table_df.iloc[:, [x_bottom, y_left_col]]
        series = QLineSeries()
        series.setName(legend_labels[y_left_col])
        for position_index, point_item in enumerate(
                left_line_data.values.tolist()):
            series.append(position_index, point_item[1])  # 取出源数据后一条线就2列数据
            # 收集坐标标签
            if not has_x_labels:
                chart.x_labels.append(point_item[0])
        chart.addSeries(series)  # 折线入图
        series.attachAxis(axis_x_bottom)
        series.attachAxis(axis_y_left)
    # 左轴范围
    axis_y_left.setRange(y_left_min, y_left_max)
    """ 根据右轴画折线 """
    for y_right_col in y_right_cols:  # 根据右轴画折线
        # 计算做轴的最值用于设置范围
        table_df[y_right_col] = table_df[y_right_col].apply(
            covert_float)  # y轴列转为浮点数值
        # 获取最值
        y_min, y_max = table_df[y_right_col].min(), table_df[y_right_col].max()
        if y_min < y_right_min:
            y_right_min = y_min
        if y_max > y_right_max:
            y_right_max = y_max
        # 取得图线的源数据作折线图
        left_line_data = table_df.iloc[:, [x_bottom, y_right_col]]
        series = QLineSeries()
        series.setName(legend_labels[y_right_col])
        for position_index, point_item in enumerate(
                left_line_data.values.tolist()):
            series.append(position_index, point_item[1])  # 取出源数据后一条线就2列数据
        chart.addSeries(series)
        series.attachAxis(axis_x_bottom)
        series.attachAxis(axis_y_right)
    # 右轴范围
    axis_y_right.setRange(y_right_min, y_right_max)
    # 设置下轴刻度标签
    # print('x轴最大值', x_bottom_max)
    x_bottom_interval = int(x_bottom_max / (tick_count - 1))
    if x_bottom_interval == 0:
        for i in range(0, x_bottom_max):
            axis_x_bottom.append(chart.x_labels[i], i)
    else:
        for i in range(0, x_bottom_max, x_bottom_interval):
            axis_x_bottom.append(chart.x_labels[i], i)
    chart.legend().setAlignment(Qt.AlignBottom)
    return chart
Ejemplo n.º 20
0
class PulseGen(QtWidgets.QMainWindow, Ui_MainWindow):

    GENERATOR_PORT = 5000

    def __init__(self, parent=None):

        super(PulseGen, self).__init__(parent)
        self.setupUi(self)
        self.pulse_gen_display = PulseGenDisplay()
        self.display_data = [0] * 500

        self.pulse_height_max = self.pulse_height_dial.maximum()
        self.pulse_height_min = self.pulse_height_dial.minimum()

        self.pulse_gen_display.pulse_height = self.pulse_height_max
        # set pulse height
        self.pulse_gen_display.pulse_height = self.pulse_height_max
        self.pulse_height_dial.setValue(self.pulse_gen_display.pulse_height)
        self.pulse_height_dial.actionTriggered.connect(self.avoid_wrapping)
        self.pulse_height_dial.valueChanged.connect(self.pulse_height_changed)

        self.pulse_height_text.setText(str(
            self.pulse_gen_display.pulse_height))

        # don't allow editing
        self.pulse_height_text.textChanged.connect(self.no_editing)

        # pulse shape
        for pulse_form in self.pulse_gen_display.pulse_shape.keys():
            self.pulse_shape_combo.addItem(pulse_form)
        self.pulse_shape_combo.currentIndexChanged.connect(
            self.pulse_shape_changed)

        current_pulse_form = self.pulse_shape_combo.currentText()
        self.pulse_gen_display.pulse_form = self.pulse_gen_display.pulse_shape[
            current_pulse_form]
        print("Current pulse form: " + current_pulse_form + " code: " +
              str(self.pulse_gen_display.pulse_form))

        for pulse_freq in self.pulse_gen_display.frequencies.keys():
            self.gen_freq_combo.addItem(pulse_freq)

        current_pulse_freq = self.gen_freq_combo.currentText()
        self.pulse_gen_display.pulse_T = self.pulse_gen_display.frequencies[
            current_pulse_freq]
        print("Current pulse T: " + str(self.pulse_gen_display.pulse_T))
        self.gen_freq_combo.currentIndexChanged.connect(
            self.pulse_freq_changed)

        for display_freq in self.pulse_gen_display.frequencies.keys():
            self.display_freq_combo.addItem(display_freq)
        self.display_freq_combo.currentIndexChanged.connect(
            self.display_freq_changed)

        current_display_freq = self.display_freq_combo.currentText()
        self.pulse_gen_display.display_T = self.pulse_gen_display.frequencies[
            current_display_freq]
        print("Current display T: " + str(self.pulse_gen_display.display_T))

        self.start_stop_pb.clicked.connect(self.start_stop_meas)
        self.connect_pb.clicked.connect(self.connect)

        self.gen_chart = QChart()
        self.gen_chart.legend().hide()
        self.x_axis = QValueAxis()
        self.x_axis.setMax(500 * self.pulse_gen_display.display_T)
        self.x_axis.setMin(0)
        self.y_axis = QValueAxis()
        self.y_axis.setMax(3.3)
        self.y_axis.setMin(0)
        self.gen_chart.addAxis(self.x_axis, Qt.AlignBottom)
        self.gen_chart.addAxis(self.y_axis, Qt.AlignLeft)
        self.generator_screen.setChart(self.gen_chart)
        # display the initial pulse
        self.pulse_gen_display.calc_pulse()
        self.pulse_gen_display.get_display_data()

        self.series = QLineSeries()

        for i in range(500):
            self.series.append(
                i * self.pulse_gen_display.display_T,
                self.pulse_gen_display.display_data[i] *
                self.pulse_gen_display.calib)
        self.gen_chart.addSeries(self.series)
        self.series.attachAxis(self.x_axis)
        self.series.attachAxis(self.y_axis)
        self.display_pulse()

        self.pulse_height_timer = QTimer()
        self.pulse_height_timer.setSingleShot(True)
        self.pulse_height_timer.timeout.connect(self.pulse_height_ready)

        self.genRunning = False
        self.actionQuit.triggered.connect(self.quit)

        self.client_socket = QTcpSocket(self)
        self.connected = False
        self.show()

    def no_editing(self):
        self.pulse_height_text.setText(str(
            self.pulse_gen_display.pulse_height))

    def avoid_wrapping(self, val):
        if val == QtWidgets.QAbstractSlider.SliderMove:
            minDistance = 1
            if self.pulse_height_dial.value() == self.pulse_height_max \
               and self.pulse_height_dial.sliderPosition()<self.pulse_height_max-minDistance:
                self.pulse_height_dial.setSliderPosition(self.pulse_height_max)
            elif self.pulse_height_dial.value() == self.pulse_height_min \
               and self.pulse_height_dial.sliderPosition()>self.pulse_height_min+minDistance:
                self.pulse_height_dial.setSliderPosition(self.pulse_height_min)

    def pulse_shape_changed(self):
        '''
        if self.genRunning:
            print("Current shape index: ",self.pulse_shape_combo.currentIndex())
            print("current pulse form: ",self.pulse_gen_display.pulse_form)
            if self.pulse_shape_combo.currentIndex() == self.pulse_gen_display.pulse_form:
                return
            QMessageBox.warning(self,
                                'Pulse generation is active',
                                'Pulse generator is running\nPlease stop pulse generation before changing parameters')
            self.pulse_shape_combo.setCurrentIndex(self.pulse_gen_display.pulse_form)
            return
        '''
        print("pulse shape changed")
        current_pulse_form = self.pulse_shape_combo.currentText()
        self.pulse_gen_display.pulse_form = self.pulse_gen_display.pulse_shape[
            current_pulse_form]
        print("Current pulse form: " + current_pulse_form + " code: " +
              str(self.pulse_gen_display.pulse_form))
        self.display_pulse()
        if not self.connected:
            return
        else:
            pulse_form_msg = "pulse_shape=" + str(
                self.pulse_gen_display.pulse_form) + "\n"
            print("Sending: " + pulse_form_msg)
            self.client_socket.write(bytes(pulse_form_msg, encoding="ascii"))
            self.client_socket.waitForReadyRead()
            responseMsg = self.client_socket.readAll()
            print("reponse msg: ", bytes(responseMsg).decode())

    def pulse_freq_changed(self):

        new_freq = self.gen_freq_combo.currentText()
        self.pulse_gen_display.pulse_T = self.pulse_gen_display.frequencies[
            new_freq]
        print("Pulse frequency changed to " + new_freq + "T: " +
              str(self.pulse_gen_display.pulse_T))
        self.display_pulse()
        '''
        if self.genRunning:
            if self.pulse_gen_display.frequencies[self.gen_freq_combo.currentText()] == self.pulse_gen_display.pulse_T:
                return

            QMessageBox.warning(self,
                                'Pulse generation is active',
                                'Pulse generator is running\nPlease stop pulse generation before changing parameters')
            index = 0
            for freq in self.pulse_gen_display.frequencies.keys():
                print("freq: ",freq)
                print("val: ",self.pulse_gen_display.frequencies[freq])
                if self.pulse_gen_display.frequencies[freq] == self.pulse_gen_display.pulse_T:
                    self.gen_freq_combo.setCurrentIndex(index)
                    break                     
                index += 1
            return
        '''
        if not self.connected:
            return
        else:
            pulse_T_msg = "pulse_T=" + str(
                self.pulse_gen_display.pulse_T) + "\n"
            print("Sending: " + pulse_T_msg)
            self.client_socket.write(bytes(pulse_T_msg, encoding="ascii"))
            self.client_socket.waitForReadyRead()
            responseMsg = self.client_socket.readAll()
            print("reponse msg: ", bytes(responseMsg).decode())

    def display_freq_changed(self):
        new_freq = self.display_freq_combo.currentText()
        self.pulse_gen_display.display_T = self.pulse_gen_display.frequencies[
            new_freq]
        self.display_pulse()

    def pulse_height_changed(self):
        self.pulse_gen_display.pulse_height = self.pulse_height_dial.value()
        self.pulse_height_text.setText(str(
            self.pulse_gen_display.pulse_height))
        self.display_pulse()
        self.pulse_height_timer.start(500)

    def pulse_height_ready(self):
        print("Timeout")
        if not self.connected:
            return
        else:
            pulse_height_msg = "pulse_height=" + str(
                self.pulse_gen_display.pulse_height) + "\n"
            print("Sending: " + pulse_height_msg)
            self.client_socket.write(bytes(pulse_height_msg, encoding="ascii"))
            self.client_socket.waitForReadyRead()
            responseMsg = self.client_socket.readAll()
            print("reponse msg: ", bytes(responseMsg).decode())

    def connect(self):
        if self.connected:
            self.client_socket.close()
            self.connected = False
            self.connect_pb.setChecked(False)
            self.connect_pb.setText("Connect to Pulse Generator")
            return
        server_ip = str(self.server_ip_text.text())
        port = self.GENERATOR_PORT
        print("Server IP: ", server_ip)
        if server_ip.find('xxx') != -1:
            print("bad IP")
            QMessageBox.about(
                self, 'Bad Server IP', 'Please give a correct Server IP\n'
                'IP is ' + server_ip)
            self.connect_pb.setChecked(False)
            return
        else:
            print("Connecting to " + server_ip + ":", port)
            self.client_socket.connectToHost(server_ip, port)
            self.client_socket.waitForConnected(1000)

        if self.client_socket.state() != QTcpSocket.ConnectedState:
            QMessageBox.warning(
                self, 'Connection failed',
                'Please check IP address and port number\nIs the server running?'
            )
            self.connect_pb.setChecked(False)
            return

        print("Connection established")
        self.connect_pb.setText("Connected")

        self.client_socket.waitForReadyRead()
        connectMsg = self.client_socket.readAll()
        msgstring = bytes(connectMsg).decode()
        print("Connection message:" + msgstring)

        print("Send generator settings")
        pulse_form_msg = "pulse_shape=" + str(
            self.pulse_gen_display.pulse_form) + "\n"
        print("Sending: " + pulse_form_msg)
        self.client_socket.write(bytes(pulse_form_msg, encoding="ascii"))
        self.client_socket.waitForReadyRead()
        responseMsg = self.client_socket.readAll()
        print("reponse msg: ", bytes(responseMsg).decode())

        pulse_T_msg = "pulse_T=" + str(self.pulse_gen_display.pulse_T) + "\n"
        print("Sending: " + pulse_T_msg)
        self.client_socket.write(bytes(pulse_T_msg, encoding="ascii"))
        self.client_socket.waitForReadyRead()
        responseMsg = self.client_socket.readAll()
        print("reponse msg: ", bytes(responseMsg).decode())

        pulse_height_msg = "pulse_height=" + str(
            self.pulse_gen_display.pulse_height) + "\n"
        print("Sending: " + pulse_height_msg)
        self.client_socket.write(bytes(pulse_height_msg, encoding="ascii"))
        self.client_socket.waitForReadyRead()
        responseMsg = self.client_socket.readAll()
        print("reponse msg: ", bytes(responseMsg).decode())

        running_msg = 'running?=\n'
        print("Sending: " + running_msg)
        self.client_socket.write(bytes(running_msg, encoding="ascii"))
        self.client_socket.waitForReadyRead()
        responseMsg = self.client_socket.readAll()
        response = bytes(responseMsg).decode()
        print("reponse msg: ", response)
        if response == 'yes\n':
            print("task is running")
        elif response == 'no\n':
            print("task is not running")
        else:
            print("Don't know if task is running")

        self.connected = True

    def start_stop_meas(self):
        if not self.connected:
            QMessageBox.about(
                self, 'You must be connected to the generator server\n'
                'please connect and try again')
            return

        if self.start_stop_pb.isChecked():
            print("Start generation")
            # send current generator settings

            self.start_stop_pb.setText("Stop Pulse Generation")
            msg = 'start=\n'
            print("Sending: " + msg)
            self.client_socket.write(msg.encode())
            self.client_socket.waitForReadyRead()
            responseMsg = self.client_socket.readAll()
            print("reponse msg: ", bytes(responseMsg).decode())
            self.genRunning = True
        else:
            print("Stop generation")
            self.start_stop_pb.setText("Start Pulse Generation")
            msg = 'stop=\n'
            self.client_socket.write(msg.encode())
            self.client_socket.waitForReadyRead()
            responseMsg = self.client_socket.readAll()
            print("reponse msg: ", bytes(responseMsg).decode())
            self.genRunning = False

    def readTrace(self):
        print("Message from the generator")
        data = self.server_socket.readAll()
        msgstring = bytes(data).decode()
        print(msgstring)
        print(data, type(data))

    def display_pulse(self):
        self.pulse_gen_display.calc_pulse()
        self.pulse_gen_display.get_display_data()

        self.x_axis.setMax(500 * self.pulse_gen_display.display_T)
        data_points = self.series.pointsVector()
        for i in range(500):
            data_points[i].setX(i * self.pulse_gen_display.display_T)
            data_points[i].setY(self.pulse_gen_display.display_data[i] *
                                self.pulse_gen_display.calib)
        self.series.replace(data_points)

    def quit(self):
        app.exit()
Ejemplo n.º 21
0
class Graph(QChartView):
	def __init__(self, parent=None):
		super().__init__(parent=parent)

		self.setpoint_temperature = None

		self.chart = QChart()
		self.chart.legend().hide()
		self.setChart( self.chart )
		self.setRenderHint(QPainter.Antialiasing)
		self.chart.setPlotAreaBackgroundBrush( QBrush(Qt.black) )
		self.chart.setPlotAreaBackgroundVisible( True )

		self.setpointTemperatureSeries = QLineSeries( self.chart )
		pen = self.setpointTemperatureSeries.pen()
		pen.setWidthF(2.)
		pen.setColor( Qt.green )
		self.setpointTemperatureSeries.setPen( pen )
		#self.setpointTemperatureSeries.setUseOpenGL( True )
		self.chart.addSeries( self.setpointTemperatureSeries )

		self.temperatureSeries = QLineSeries( self.chart )
		pen = self.temperatureSeries.pen()
		pen.setWidthF(2.)
		pen.setColor( Qt.red )
		self.temperatureSeries.setPen( pen )
		#self.temperatureSeries.setUseOpenGL( True )
		self.chart.addSeries( self.temperatureSeries )

		self.number_of_samples_to_keep = 2 * 5 * 60

		self.xMin = QDateTime.currentDateTime().toMSecsSinceEpoch()
		self.xMax = QDateTime.currentDateTime().toMSecsSinceEpoch()
		self.yMin = 400
		self.yMax = 0

		#self.chart.createDefaultAxes()
		#x_axis = QValueAxis()
		x_axis = QDateTimeAxis()
		x_axis.setTitleText( "Time" )
		x_axis.setFormat("HH:mm:ss")
		self.chart.addAxis( x_axis, Qt.AlignBottom )
		self.temperatureSeries.attachAxis( x_axis )
		self.setpointTemperatureSeries.attachAxis( x_axis )
		startDate = QDateTime.currentDateTime().addSecs( -5 * 60 )
		endDate = QDateTime.currentDateTime().addSecs( 5 * 60 )
		#startDate = QDateTime(QDate(2017, 1, 9), QTime(17, 25, 0))
		#endDate = QDateTime(QDate(2017, 1, 9), QTime(17, 50, 0))
		#self.chart.axisX().setRange( startDate, endDate )
		#self.chart.axisX().setRange( 0, 100 )

		y_axis = QValueAxis()
		y_axis.setTitleText( "Temperature (K)" )
		self.chart.addAxis( y_axis, Qt.AlignLeft )
		self.temperatureSeries.attachAxis( y_axis )
		self.setpointTemperatureSeries.attachAxis( y_axis )
		self.chart.axisY().setRange( 0, 400 )
		#self.chart.axisY().setRange( 260., 290. )

		self.temperatureSeries.pointAdded.connect( self.Rescale_Axes )
		#self.setpointTemperatureSeries.pointAdded.connect( self.Rescale_Axes )

		self.setRubberBand( QChartView.HorizontalRubberBand )

		# Customize chart title
		font = QFont()
		font.setPixelSize(24);
		self.chart.setTitleFont(font);
		self.chart.setTitleBrush(QBrush(Qt.white));

		## Customize chart background
		#backgroundGradient = QLinearGradient()
		#backgroundGradient.setStart(QPointF(0, 0));
		#backgroundGradient.setFinalStop(QPointF(0, 1));
		#backgroundGradient.setColorAt(0.0, QColor(0x000147));
		#backgroundGradient.setColorAt(1.0, QColor(0x000117));
		#backgroundGradient.setCoordinateMode(QGradient.ObjectBoundingMode);
		#self.chart.setBackgroundBrush(backgroundGradient);
		transparent_background = QBrush(QColor(0,0,0,0))
		self.chart.setBackgroundBrush( transparent_background )

		# Customize axis label font
		labelsFont = QFont()
		labelsFont.setPixelSize(16);
		x_axis.setLabelsFont(labelsFont)
		y_axis.setLabelsFont(labelsFont)
		x_axis.setTitleFont(labelsFont)
		y_axis.setTitleFont(labelsFont)

		# Customize axis colors
		axisPen = QPen(QColor(0xd18952))
		axisPen.setWidth(2)
		x_axis.setLinePen(axisPen)
		y_axis.setLinePen(axisPen)

		# Customize axis label colors
		axisBrush = QBrush(Qt.white)
		x_axis.setLabelsBrush(axisBrush)
		y_axis.setLabelsBrush(axisBrush)
		x_axis.setTitleBrush(axisBrush)
		y_axis.setTitleBrush(axisBrush)

	def set_title(self, title):
		self.chart.setTitle(title)

	def add_new_data_point( self, x, y ):
		x_as_millisecs = x.toMSecsSinceEpoch()
		self.temperatureSeries.append( x_as_millisecs, y )
		if( self.setpoint_temperature ):
			self.setpointTemperatureSeries.append( x_as_millisecs, self.setpoint_temperature )

		num_of_datapoints = self.temperatureSeries.count()
		#if( num_of_datapoints > self.number_of_samples_to_keep ):
		#	self.number_of_samples_to_keep.
		#print( x_as_millisecs, y )
		#self.chart.scroll( x_as_millisecs - 5 * 60 * 1000, x_as_millisecs )
		#self.temperatureSeries.append( x, float(y) )
		#self.repaint()

	def Rescale_Axes( self, index ):
		x = self.temperatureSeries.at( index ).x()
		x_rescaled = False
		if( x < self.xMin ):
			self.xMin = x
			x_rescaled = True
		if( x > self.xMax ):
			self.xMax = x
			x_rescaled = True
		if( x_rescaled ):
			full_range = min( self.xMax - self.xMin, 5 * 60 * 1000 )
			margin = full_range * 0.05

			self.chart.axisX().setRange( QDateTime.fromMSecsSinceEpoch(self.xMax - full_range - margin), QDateTime.fromMSecsSinceEpoch(self.xMax + margin) )
			
		y = self.temperatureSeries.at( index ).y()
		y_rescaled = False
		if( y < self.yMin ):
			self.yMin = y
			y_rescaled = True
		if( y > self.yMax ):
			self.yMax = y
			y_rescaled = True
		if( y_rescaled ):
			full_range = self.yMax - self.yMin
			margin = full_range * 0.05
			self.chart.axisY().setRange( self.yMin - margin, self.yMax + margin )
			
Ejemplo n.º 22
0
    sunSpots.close()
    # [2]

    # [3] create the chart
    chart = QChart()
    chart.addSeries(series)
    chart.setTitle("Sunspots count (by Space Weather Prediction Center)")
    # [3]

    # [4]
    axisX = QDateTimeAxis()
    axisX.setTickCount(10)
    axisX.setFormat("MMM yyyy")
    axisX.setTitleText("Date")
    chart.addAxis(axisX, Qt.AlignBottom)
    series.attachAxis(axisX)

    axisY = QValueAxis()
    axisY.setLabelFormat("%i")
    axisY.setTitleText("Sunspots count")
    chart.addAxis(axisY, Qt.AlignLeft)
    series.attachAxis(axisY)
    # [4]

    # [5] prepare the chart view
    chartView = QChartView(chart)
    chartView.setRenderHint(QPainter.Antialiasing)
    # [5]

    # [6] show the main window
    window = QMainWindow()
Ejemplo n.º 23
0
    def create_piechart(self):
        series = QLineSeries()

        weights = SQLStatements.getallWeightChanges(self.userID)
        print(weights)

        weights = str(weights)
        weights = weights.replace("(", "")
        weights = weights.replace(")", "")
        weights = weights.replace(",", "")
        weights = weights.replace("[", "")
        weights = weights.replace("]", "")

        weightsTable = weights.split()

        print(weightsTable)

        count = 0
        for x in weightsTable:
            x = int(float(x))
            print(x)
            series.append(count, x)
            count = count + 2

        chart = QChart()

        chart.addSeries(series)
        chart.setAnimationOptions(QChart.SeriesAnimations)
        chart.setTitle("Weight Change over time")
        chart.setTheme(QChart.ChartThemeBlueCerulean)
        chart.setBackgroundVisible(False)

        #Title Font size
        font = QFont("Sans Serif", )
        font.setPixelSize(18)
        chart.setTitleFont(font)

        # X Axis Settings
        axisX = QValueAxis()
        axisX.setTitleText("Time")

        # Y Axis Settings
        axisY = QValueAxis()
        axisY.setTitleText("Weight (KG)")

        # Customize axis label font
        Lfont = QFont("Sans Serif")
        Lfont.setPixelSize(16)
        axisX.setLabelsFont(Lfont)
        axisY.setLabelsFont(Lfont)

        #add Axis
        chart.addAxis(axisX, Qt.AlignBottom)
        series.attachAxis(axisX)

        chart.addAxis(axisY, Qt.AlignLeft)
        series.attachAxis(axisY)

        chartview = QChartView(chart)
        chartview.setRenderHint(QPainter.Antialiasing)

        return chartview
Ejemplo n.º 24
0
angularAxis.setTickCount(9)
angularAxis.setLabelFormat('%.1f')
angularAxis.setShadesVisible(True)
angularAxis.setShadesBrush(QBrush(QColor(249, 249, 255)))
chart.addAxis(angularAxis, QPolarChart.PolarOrientationAngular)

radialAxis = QValueAxis()
radialAxis.setTickCount(9)
radialAxis.setLabelFormat('%d')
chart.addAxis(radialAxis, QPolarChart.PolarOrientationRadial)

series1.attachAxis(radialAxis)
series1.attachAxis(angularAxis)
series2.attachAxis(radialAxis)
series2.attachAxis(angularAxis)
series3.attachAxis(radialAxis)
series3.attachAxis(angularAxis)
series4.attachAxis(radialAxis)
series4.attachAxis(angularAxis)
series5.attachAxis(radialAxis)
series5.attachAxis(angularAxis)

radialAxis.setRange(RADIAL_MIN, RADIAL_MAX)
angularAxis.setRange(ANGULAR_MIN, ANGULAR_MAX)

chartView = ChartView()
chartView.setChart(chart)
chartView.setRenderHint(QPainter.Antialiasing)

window = QMainWindow()
window.setCentralWidget(chartView)
Ejemplo n.º 25
0
    def onPlotButtonClicked(self):
        if self.chart:
            self.chart.removeAllSeries()
        if not self.data:
            return
        self.showMessage('Preparing plot ...')
        name = self.paramNameEdit.text()
        packet_selection = self.comboBox.currentIndex()
        xaxis_type = self.xaxisComboBox.currentIndex()
        data_type = self.dataTypeComboBox.currentIndex()

        timestamp = []
        self.y = []
        packet_id = self.current_row
        params = self.data[packet_id]['parameters']
        header = self.data[packet_id]['header']
        current_spid=header['SPID']
        if packet_selection == 0:
            self.walk(
                name,
                params,
                header,
                timestamp,
                self.y,
                xaxis_type,
                data_type)
        elif packet_selection == 1:
            for packet in self.data:
                header = packet['header']
                if packet['header']['SPID'] != current_spid:
                    continue
                #only look for parameters in the packets of the same type
                params = packet['parameters']
                self.walk(
                    name,
                    params,
                    header,
                    timestamp,
                    self.y,
                    xaxis_type,
                    data_type)

        self.x = []



        if not self.y:
            self.showMessage('No data points')
        elif self.y:
            style = self.styleEdit.text()
            if not style:
                style = '-'
            title = '%s' % str(name)
            desc = self.descLabel.text()
            if desc:
                title += '- %s' % desc

            self.chart.setTitle(title)

            ylabel = 'Raw value'
            xlabel = name
            if data_type == 1:
                ylabel = 'Engineering  value'
            if xaxis_type == 0:
                xlabel = "Packet #"
                self.x = range(0, len(self.y))
            if xaxis_type == 1:
                self.x = [t - timestamp[0] for t in timestamp]
                xlabel = 'Time -T0 (s)'

            #if xaxis_type != 2:
            if True:
                series = QLineSeries()
                series2 = None

                # print(y)
                # print(x)
                for xx, yy in zip(self.x, self.y):
                    series.append(xx, yy)

                if 'o' in style:
                    series2 = QScatterSeries()
                    for xx, yy in zip(self.x, self.y):
                        series2.append(xx, yy)
                    self.chart.addSeries(series2)
                self.chart.addSeries(series)

                self.showMessage('plotted!')

                #self.chart.createDefaultAxes()
                axisX = QValueAxis()
                axisX.setTitleText(xlabel)
                axisY = QValueAxis()
                axisY.setTitleText(ylabel)

                self.chart.setAxisX(axisX)
                self.chart.setAxisY(axisY)
                series.attachAxis(axisX)
                series.attachAxis(axisY)

                # histogram
            #else:
            #    nbins = len(set(self.y))
            #    ycounts, xedges = np.histogram(self.y, bins=nbins)
            #    series = QLineSeries()
            #    for i in range(0, nbins):
            #        meanx = (xedges[i] + xedges[i + 1]) / 2.
            #        series.append(meanx, ycounts[i])
            #    # series.append(dataset)
            #    self.chart.addSeries(series)
            #    #self.chart.createDefaultAxes()
            #    self.showMessage('Histogram plotted!')

            #    axisX = QValueAxis()

            #    axisX.setTitleText(name)
            #    axisY = QValueAxis()

            #    axisY.setTitleText("Counts")

            #    self.chart.setAxisY(axisY)
            #    self.chart.setAxisX(axisX)
            ##    series.attachAxis(axisX)
            #    series.attachAxis(axisY)

            # self.widget.setChart(self.chart)
            self.xlabel=xlabel
            self.ylabel=ylabel
            self.chartView.setRubberBand(QChartView.RectangleRubberBand)
            self.chartView.setRenderHint(QtGui.QPainter.Antialiasing)
Ejemplo n.º 26
0
class ChartView(QChartView):
    def __init__(self, no_margins=False):
        super().__init__()
        self.__last_mouse_pos = None
        self.lineSeries = QLineSeries()
        # self.lineSeries.setPointsVisible(True)
        self.no_margins = no_margins

        #Create a menu by right click on QChartView
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.show_context_menu)

        ##Axis cofnig
        self.x_time_scaled = False
        self.x_name = None
        self.y_name = None
        self.x_tick_num = 30
        self.y_tick_num = 20
        self.x_label_angle = -90
        self.y_label_angle = 0
        self.y_min = None
        self.y_max = None
        self.x_min = None
        self.x_max = None

    def mousePressEvent(self, event: QMouseEvent):
        if event.button() == Qt.MiddleButton:
            self.__last_mouse_pos = event.pos()
            event.accept()

        QChartView.mousePressEvent(self, event)

    def mouseMoveEvent(self, event: QMouseEvent):
        if event.buttons() & Qt.MiddleButton:
            dif_pos = event.pos() - self.__last_mouse_pos

            self.chart().scroll(-dif_pos.x(), dif_pos.y())
            event.accept()

            self.__last_mouse_pos = event.pos()

        QChartView.mouseMoveEvent(self, event)

    def wheelEvent(self, event: QWheelEvent):
        factor = event.angleDelta().y()
        if factor < 0:
            self.chart().zoom(0.75)
        else:
            self.chart().zoom(1.25)

    def show_context_menu(self, pos: QPoint):
        menu = QMenu()

        plot_save_action = QAction('Сохранить график', self)
        plot_save_action.triggered.connect(self.save_plot)
        menu.addAction(plot_save_action)

        menu.exec(self.mapToGlobal(pos))

    def save_plot(self):
        pixmap = self.grab()

        pixmap_name = QFileDialog.getSaveFileName(
            self, 'Сохранение графика', None,
            "PNG (*.png);;JPG (*.jpg);;BMP (*.bmp)")[0]

        if not pixmap_name:
            return

        pixmap.save(pixmap_name, os.path.splitext(pixmap_name)[1][1:])

    def make_axis(self):
        if self.x_time_scaled:
            axis_x = QDateTimeAxis()
            axis_x.setFormat("yyyy-MM-dd HH:mm:ss")
            axis_x.setTitleText("Время")
        else:
            axis_x = QValueAxis()
            axis_x.setTitleText(self.x_name)

        if self.x_min:
            axis_x.setMin(self.x_min)
        if self.x_max:
            axis_x.setMax(self.x_max)

        axis_x.setLabelsAngle(self.x_label_angle)
        axis_x.setTickCount(self.x_tick_num)

        axis_y = QValueAxis()
        if self.y_min:
            axis_y.setMin(self.y_min)
        if self.y_max:
            axis_y.setMax(self.y_max)

        axis_y.setTitleText(self.y_name)
        axis_y.setTickCount(self.y_tick_num)
        axis_y.setLabelsAngle(self.y_label_angle)

        return axis_x, axis_y

    def build_plot(self,
                   data,
                   title,
                   is_legend_visible=False,
                   series_name=None):
        axis_x, axis_y = self.make_axis()

        chart = QChart()
        if self.no_margins:
            chart.setMargins(QMargins(0, 0, 0, 0))

        self.clean()

        if data != None:
            self.lineSeries = self.fill_series(data)
            self.lineSeries.setName(series_name)

        chart.addSeries(self.lineSeries)
        chart.legend().setVisible(is_legend_visible)
        chart.setTitle(title)
        chart.addAxis(axis_x, Qt.AlignBottom)
        chart.addAxis(axis_y, Qt.AlignLeft)

        self.lineSeries.attachAxis(axis_x)
        self.lineSeries.attachAxis(axis_y)

        self.setChart(chart)

    def build_multiple_plot(self, first_data, second_data, title):
        axis_x, axis_y = self.make_axis()

        chart = QChart()
        if self.no_margins:
            chart.setMargins(QMargins(0, 0, 0, 0))

        self.clean()

        first_lineseries = self.fill_series(first_data)
        second_lineseries = self.fill_series(second_data)

        chart.addSeries(first_lineseries)
        chart.addSeries(second_lineseries)
        chart.addAxis(axis_x, Qt.AlignBottom)
        chart.addAxis(axis_y, Qt.AlignLeft)
        chart.legend().setVisible(False)
        chart.setTitle(title)

        first_lineseries.attachAxis(axis_x)
        first_lineseries.attachAxis(axis_y)

        second_lineseries.attachAxis(axis_x)
        second_lineseries.attachAxis(axis_y)

        first_lineseries.setPointsVisible(True)
        second_lineseries.setPointsVisible(True)

        self.setChart(chart)

    def series_append(self, x, y, x_min, y_min, x_range=False, y_range=False):
        self.lineSeries.append(x, y)

        self.chart().axisX().setMin(x_min)
        self.chart().axisY().setMin(y_min - 0.2)

        if x_range:
            self.chart().axisX().setMax(x)

        if y_range:
            self.chart().axisY().setMax(y + 0.2)

    def add_series(self, data, series_name=None):
        series = self.fill_series(data)
        series.setName(series_name)

        self.chart().addSeries(series)

        series.attachAxis(self.chart().axisX())
        series.attachAxis(self.chart().axisY())

    def fill_series(self, data):
        series = QLineSeries()
        series.setPointsVisible(True)

        xf = data[0]
        yf = data[1]

        for i in range(len(xf)):
            series.append(xf[i], yf[i])

        return series

    def clean(self):
        self.lineSeries.clear()
Ejemplo n.º 27
0
    def onPlotButtonClicked(self, packets=None):
        if self.chart:
            self.chart.removeAllSeries()
        if packets is None:
            packets = self.data
        if not packets:
            return

        self.showMessage('Preparing plot ...')
        name = self.paramNameEdit.text()
        packet_selection = self.comboBox.currentIndex()
        xaxis_type = self.xaxisComboBox.currentIndex()
        data_type = self.dataTypeComboBox.currentIndex()
        timestamp = []
        self.y = []
        params = self.paramNameEdit.text()
        header = packets[0]['header']
        current_spid = 0
        spid_text = self.spidLineEdit.text()
        if spid_text:
            current_spid = int(spid_text)
        selected_packets=[] 
        if packet_selection == 0:
            selected_packets=[packets[self.current_row]]
        elif packet_selection == 1:
            selected_packets=packets

        for packet in selected_packets:
            header = packet['header']
            if packet['header']['SPID'] != current_spid:
                continue
            params = packet['parameters']
            self.walk(name, params, header, timestamp, self.y, xaxis_type,
                      data_type)


        self.x = []

        if not self.y:
            self.showMessage('No data points')
        elif self.y:
            style = self.styleEdit.text()
            if not style:
                style = '-'
            title = '%s' % str(name)
            desc = self.descLabel.text()
            if desc:
                title += '- %s' % desc

            self.chart.setTitle(title)

            ylabel = 'Raw value'
            xlabel = name
            if data_type == 1:
                ylabel = 'Engineering / Decompressed  value'
            if xaxis_type == 0:
                if packet_selection == 1:
                    xlabel = "Packet #"
                else:
                    xlabel = "Repeat #"
                self.x = range(0, len(self.y))
            if xaxis_type == 1:
                self.x = [t - timestamp[0] for t in timestamp]
                xlabel = 'Time -T0 (s)'

            if xaxis_type != 2:
                series = QLineSeries()
                series2 = None
                for xx, yy in zip(self.x, self.y):
                    series.append(xx, yy)
                if 'o' in style:
                    series2 = QScatterSeries()
                    for xx, yy in zip(self.x, self.y):
                        series2.append(xx, yy)
                    self.chart.addSeries(series2)
                self.chart.addSeries(series)
                axisX = QValueAxis()
                axisX.setTitleText(xlabel)
                axisY = QValueAxis()
                axisY.setTitleText(ylabel)

                self.chart.setAxisX(axisX)
                self.chart.setAxisY(axisY)
                series.attachAxis(axisX)
                series.attachAxis(axisY)
            else:
                nbins = len(set(self.y))
                ycounts, xedges = np.histogram(self.y, bins=nbins)
                series = QLineSeries()
                for i in range(0, nbins):
                    meanx = (xedges[i] + xedges[i + 1]) / 2.
                    series.append(meanx, ycounts[i])
                self.chart.addSeries(series)
                axisX = QValueAxis()
                axisX.setTitleText(name)
                axisY = QValueAxis()
                axisY.setTitleText("Counts")

                self.chart.setAxisY(axisY)
                self.chart.setAxisX(axisX)
                series.attachAxis(axisX)
                series.attachAxis(axisY)

            self.xlabel = xlabel
            self.ylabel = ylabel
            self.chartView.setRubberBand(QChartView.RectangleRubberBand)
            self.chartView.setRenderHint(QtGui.QPainter.Antialiasing)
            msg = 'Number of data points: {}, Ymin: {}, Ymax: {}'.format(
                len(self.y), min(self.y), max(self.y))
            self.showMessage(msg, 1)

            self.showMessage('The canvas updated!')
Ejemplo n.º 28
0
   def do_redrawFill(self):
      self.chart.removeAllSeries()  #删除所有序列
      pen=QPen(self.__colorLine)    #线条颜色
      pen.setWidth(2)

      seriesFullWave = QLineSeries()      #全波形
      seriesFullWave.setUseOpenGL(True)
      seriesFullWave.setPen(pen)

      seriesPositive = QLineSeries()      #正半部分曲线
      seriesPositive.setUseOpenGL(True)
      seriesPositive.setVisible(False)    #不显示

      seriesNegative = QLineSeries()      #负半部分曲线
      seriesNegative.setUseOpenGL(True)
      seriesNegative.setVisible(False)    #不显示即可

      seriesZero = QLineSeries()          #零均值线
      seriesZero.setUseOpenGL(True)
      seriesZero.setVisible(False)        #不显示即可

   ## 填充数据
      vx=0
      intv=0.001   #1000Hz采样,数据点间隔时间
      pointCount=len(self.__vectData)
      for i in range(pointCount):
         value=self.__vectData[i]
         seriesFullWave.append(vx,value)  #完整波形
         seriesZero.append(vx,0)          #零值线
         if value>0:
            seriesPositive.append(vx,value)  #正半部分波形
            seriesNegative.append(vx,0)
         else:
            seriesPositive.append(vx,0)
            seriesNegative.append(vx,value) #负半部分波形
         vx =vx+intv

      self.__axisX.setRange(0,vx)

   ##  创建QAreaSeries序列,设置上、下界的QLineSeries对象
      pen.setStyle(Qt.NoPen)  #无线条,隐藏填充区域的边线
      if self.ui.radioFill_Pos.isChecked():     #positive fill
         series = QAreaSeries(seriesPositive, seriesZero) #QAreaSeries
         series.setColor(self.__colorFill)      #填充色
         series.setPen(pen)   #不显示线条
         self.chart.addSeries(series)
         series.attachAxis(self.__axisX)
         series.attachAxis(self.__axisY)
         
      elif self.ui.radioFill_Neg.isChecked():  #negative fill
         series = QAreaSeries(seriesZero,seriesNegative)
         series.setColor(self.__colorFill)
         series.setPen(pen)   #不显示线条
         self.chart.addSeries(series)
         series.attachAxis(self.__axisX)
         series.attachAxis(self.__axisY)

      elif self.ui.radioFill_Both.isChecked():  #both fill
         series = QAreaSeries(seriesZero,seriesFullWave)
         series.setColor(self.__colorFill)
         series.setPen(pen)   #不显示线条
         self.chart.addSeries(series)
         series.attachAxis(self.__axisX)
         series.attachAxis(self.__axisY)

      series.clicked.connect(self.do_area_clicked)  #关联槽函数
         
   ## 构建QAreaSeries的两个QLineSeries序列必须添加到chart里,否则程序崩溃
      self.chart.addSeries(seriesZero)       #隐藏
      self.chart.addSeries(seriesPositive)   #隐藏
      self.chart.addSeries(seriesNegative)   #隐藏
      self.chart.addSeries(seriesFullWave)   #全波形曲线,显示

      seriesPositive.attachAxis(self.__axisX)
      seriesPositive.attachAxis(self.__axisY)

      seriesNegative.attachAxis(self.__axisX)
      seriesNegative.attachAxis(self.__axisY)

      seriesZero.attachAxis(self.__axisX)
      seriesZero.attachAxis(self.__axisY)
      
      seriesFullWave.attachAxis(self.__axisX)
      seriesFullWave.attachAxis(self.__axisY)
        def __init__(self, parent=None):
            super(Widget, self).__init__(parent)
            self.setWindowTitle('Financieële grafieken externe werken')
            self.setWindowIcon(QIcon('./images/logos/logo.jpg'))
            self.setWindowFlags(self.windowFlags() | Qt.WindowSystemMenuHint
                                | Qt.WindowMinMaxButtonsHint)

            grid = QGridLayout()
            grid.setSpacing(20)

            metadata = MetaData()
            resultaten = Table('resultaten', metadata,
                               Column('resID', Integer(), primary_key=True),
                               Column('statusweek', String),
                               Column('btotaal', Float),
                               Column('wtotaal', Float),
                               Column('betaald_bedrag', Float),
                               Column('meerminderwerk', Float),
                               Column('onderhandenwerk', Float),
                               Column('aanneemsom', Float),
                               Column('blonen', Float),
                               Column('wlonen', Float),
                               Column('bmaterialen', Float),
                               Column('wmaterialen', Float),
                               Column('bmaterieel', Float),
                               Column('wmaterieel', Float),
                               Column('bprojectkosten', Float),
                               Column('wprojectkosten', Float),
                               Column('binhuur', Float),
                               Column('winhuur', Float),
                               Column('bdiensten', Float),
                               Column('wdiensten', Float),
                               Column('bruto_winst', Float),
                               Column('boekweek', String))
            params = Table('params', metadata,
                           Column('paramID', Integer(), primary_key=True),
                           Column('tarief', String))
            engine = create_engine(
                'postgresql+psycopg2://postgres@localhost/bisystem')
            con = engine.connect()

            selpar1 = select([params]).where(params.c.paramID == 97)
            rppar1 = con.execute(selpar1).first()
            bo_incr = rppar1[1] / 52  #begrote omzet per week
            selpar2 = select([params]).where(params.c.paramID == 98)
            rppar2 = con.execute(selpar2).first()
            bw_incr = rppar2[1] / 52  #begrote winst per week

            jaar = jrwk[0:4]
            engine = create_engine(
                'postgresql+psycopg2://postgres@localhost/bisystem')
            con = engine.connect()
            selres = select([resultaten]).where(and_(resultaten.c.boekweek == jrwk,\
              resultaten.c.statusweek.like(jaar+'%'))).order_by(resultaten.c.statusweek)
            rpres = con.execute(selres)
            if keuze == '1':
                s1 = 2
                s2 = 3
                t1 = 'Kosten totaal begroot'
                t2 = 'Kosten totaal werkelijk'
                t3 = 'Kosten totaal '
                c1 = Qt.red
                c2 = Qt.blue
                ysch = 160000000
            elif keuze == '2':
                s1 = 8
                s2 = 9
                t1 = 'Lonen begroot'
                t2 = 'Lonen werkelijk'
                t3 = 'Lonen '
                c1 = Qt.green
                c2 = Qt.darkBlue
                ysch = 100000000
            elif keuze == '3':
                s1 = 10
                s2 = 11
                t1 = 'Materialen begroot'
                t2 = 'Materialen werkelijk'
                t3 = 'Materialen'
                c1 = Qt.cyan
                c2 = Qt.magenta
                ysch = 60000000
            elif keuze == '4':
                s1 = 12
                s2 = 13
                t1 = 'Materiëel begroot'
                t2 = 'Materiëel werkelijk'
                t3 = 'Materiëel '
                c1 = Qt.darkYellow
                c2 = Qt.darkGreen
                ysch = 20000000
            elif keuze == '5':
                s1 = 16
                s2 = 17
                t1 = 'Inhuur begroot'
                t2 = 'Inhuur werkelijk'
                t3 = 'Inhuur '
                c1 = Qt.darkBlue
                c2 = Qt.darkRed
                ysch = 30000000
            elif keuze == '6':
                s1 = 18
                s2 = 19
                t1 = 'Diensten begroot'
                t2 = 'Diensten werkelijk'
                t3 = 'Diensten '
                c1 = Qt.red
                c2 = Qt.blue
                ysch = 30000000
            elif keuze == '7':
                s1 = 14
                s2 = 15
                t1 = 'Projektkosten begroot'
                t2 = 'Projektkosten werkelijk'
                t3 = 'Projektkosten '
                c1 = Qt.darkYellow
                c2 = Qt.darkCyan
                ysch = 10000000
            elif keuze == '8':
                y3 = [
                    0,
                ]
                y3val = 0
                x1 = [
                    0,
                ]
                xval1 = 0
                # prognose winst
                for teller in range(0, 53):
                    y3val = y3val + bw_incr
                    y3 = y3 + [(y3val)]
                    xval1 = xval1 + 1
                    x1 = x1 + [(xval1)]
                s1 = 20
                s2 = 20
                t1 = 'Bruto winst prognose'
                t2 = 'Bruto winst actueel'
                t3 = 'Bruto winst - prognose / aktueel '
                c1 = Qt.darkCyan
                c2 = Qt.darkMagenta
                ysch = 20000000
            elif keuze == '9':
                s1 = 6
                s2 = 4
                t1 = 'Onderhandenwerk'
                t2 = 'Betaald bedrag'
                t3 = 'Onderhandenwerk - Betaald bedrag '
                c1 = Qt.yellow
                c2 = Qt.green
                ysch = 160000000
            elif keuze == 'A':
                y4 = [
                    0,
                ]
                y4val = 0
                x2 = [
                    0,
                ]
                xval2 = 0
                #prognose omzet
                for teller in range(0, 53):
                    y4val = y4val + bo_incr
                    y4 = y4 + [(y4val)]
                    xval2 = xval2 + 1
                    x2 = x2 + [(xval2)]
                s1 = 7
                s2 = 7
                t1 = 'Omzet prognose'
                t2 = 'Omzet aktueel'
                t3 = 'Omzet '
                c1 = Qt.red
                c2 = Qt.blue
                ysch = 160000000
            elif keuze == 'B':
                s1 = 20
                s2 = 5
                t1 = 'Bruto winst werkelijk'
                t2 = 'Meerminderwerk'
                t3 = 'Bruto winst werkelijk / Meerminderwerk '
                c1 = Qt.darkRed
                c2 = Qt.darkBlue
                ysch = 30000000

            x = [
                0,
            ]
            y1 = [
                0,
            ]
            y2 = [
                0,
            ]
            idx = 0
            yval1 = 0
            yval2 = 0
            for row in rpres:
                yval1 = y1[idx] + row[s1]
                y1 = y1 + [(yval1)]
                yval2 = y2[idx] + row[s2]
                y2 = y2 + [(yval2)]
                x = x + [(int(row[1][4:]))]
                idx += 1

            series1 = QLineSeries()
            if keuze == '8':
                for t, val in zip(x1, y3):
                    series1.append(int(t), val)
            elif keuze == 'A':
                for t, val in zip(x2, y4):
                    series1.append(int(t), val)
            else:
                for t, val in zip(x, y1):
                    series1.append(int(t), val)
            series2 = QLineSeries()
            for t, val in zip(x, y2):
                series2.append(int(t), val)

            chart = QChart()
            chart.addSeries(series1)
            chart.addSeries(series2)

            series1.setColor(QColor(c1))
            series2.setColor(QColor(c2))
            series1.setName(t1)
            series2.setName(t2)
            chart.legend().setVisible(True)

            font = QFont()
            font.setPixelSize(22)
            chart.setTitleFont(font)
            chart.setTitle(t3 + jaar)
            chart.setTitleBrush(QBrush(Qt.black))
            chart.legend().setLabelBrush(QColor(Qt.black))

            axisX = QCategoryAxis()
            axisY = QCategoryAxis()

            axisX.setTitleText('Jaar ' + jaar + ' - Weeknummers')
            axisX.setTitleBrush(QBrush(Qt.black))
            font = QFont("Sans Serif")
            axisX.setTitleFont(font)

            axisPen = QPen(QColor(100, 100, 100))  # 100,100,100
            axisPen.setWidth(3)
            axisX.setLinePen(axisPen)
            axisY.setLinePen(axisPen)

            axisBrush = QBrush(Qt.black)
            axisX.setLabelsBrush(axisBrush)
            axisY.setLabelsBrush(axisBrush)

            axisX.setGridLineVisible(False)
            axisY.setGridLineVisible(True)
            axisX.setShadesBrush(QBrush(QColor(245, 245, 245)))
            axisX.setShadesVisible(True)
            for x in range(1, 54):
                axisX.append(jaar + "-" + ("0" + str(x))[-2:], x)
            axisX.setRange(0, 53)
            axisX.setLabelsAngle(-90)

            axisY = QValueAxis()
            axisY.setTickCount(33)
            axisY.setTitleText("Bedragen in Euro")
            axisY.setTitleFont(font)
            axisY.setLabelFormat('%d')
            axisY.setTitleBrush(QBrush(Qt.black))
            axisY.setRange(0, ysch)  #disable for automatic Y scale
            #axisY.applyNiceNumbers() #enable by automatic Y scale

            Lfont = QFont("Sans Serif")
            Dfont = QFont("Sans Serif")
            Lfont.setPixelSize(10)
            Dfont.setPixelSize(10)
            axisX.setLabelsFont(Dfont)
            axisY.setLabelsFont(Lfont)

            axisPen = QPen(QColor('black'))
            axisPen = QPen()
            axisPen.setWidth(2)
            axisX.setLinePen(axisPen)
            axisX.setLabelsColor(QColor('black'))
            axisY.setLinePen(axisPen)
            axisY.setLabelsColor(QColor('black'))

            chart.addAxis(axisX, Qt.AlignBottom)
            series1.attachAxis(axisX)
            axisX.setLabelsAngle(-90)

            chart.addAxis(axisY, Qt.AlignLeft)
            series1.attachAxis(axisY)
            series2.attachAxis(axisY)

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

            buttonPreview = QPushButton('Afdrukvoorbeeld')
            buttonPreview.clicked.connect(self.handle_preview)
            buttonPreview.setStyleSheet(
                "color: black;  background-color: gainsboro")
            buttonPrint = QPushButton('Printen')
            buttonPrint.clicked.connect(self.handle_print)
            buttonPrint.setStyleSheet(
                "color: black;  background-color: gainsboro")
            buttonSluit = QPushButton('Sluiten')
            buttonSluit.clicked.connect(lambda: sluit(self, m_email))
            buttonSluit.setStyleSheet(
                "color: black;  background-color: gainsboro")
            grid.addWidget(self.chartView, 0, 0, 0, 3)
            grid.addWidget(buttonSluit, 1, 0)
            grid.addWidget(buttonPrint, 1, 1)
            grid.addWidget(buttonPreview, 1, 2)

            self.setLayout(grid)
            self.setGeometry(200, 40, 1395, 930)
Ejemplo n.º 30
0
    def initChart(self):
        series = QLineSeries()

        data = [
            QPoint(0, 4),
            QPoint(3, 2),
            QPoint(7, 7),
            QPoint(9, 10),
            QPoint(12, 17),
            QPoint(17, 9),
            QPoint(20, 22),
            QPoint(22, 2),
            QPoint(28, 13)
        ]

        series.append(data)

        # creating chart object
        chart = QChart()
        chart.legend().hide()
        chart.addSeries(series)

        pen = QPen(QColor(0, 0, 128))
        pen.setWidth(3)
        series.setPen(pen)

        font = QFont("Open Sans")
        font.setPixelSize(40)
        font.setBold(True)
        chart.setTitleFont(font)
        chart.setTitleBrush(QBrush(Qt.yellow))
        chart.setTitle("Custom Chart Demo")

        backgroundGradient = QLinearGradient()
        backgroundGradient.setStart(QPoint(0, 0))
        backgroundGradient.setFinalStop(QPoint(0, 1))
        backgroundGradient.setColorAt(0.0, QColor(175, 201, 182))
        backgroundGradient.setColorAt(1.0, QColor(51, 105, 66))
        backgroundGradient.setCoordinateMode(QGradient.ObjectBoundingMode)
        chart.setBackgroundBrush(backgroundGradient)

        plotAreaGraident = QLinearGradient()
        plotAreaGraident.setStart(QPoint(0, 1))
        plotAreaGraident.setFinalStop(QPoint(1, 0))
        plotAreaGraident.setColorAt(0.0, QColor(222, 222, 222))
        plotAreaGraident.setColorAt(1.0, QColor(51, 105, 66))
        plotAreaGraident.setCoordinateMode(QGradient.ObjectBoundingMode)
        chart.setPlotAreaBackgroundBrush(plotAreaGraident)
        chart.setPlotAreaBackgroundVisible(True)

        # customize axis
        axisX = QCategoryAxis()
        axisY = QCategoryAxis()

        labelFont = QFont("Open Sans")
        labelFont.setPixelSize(25)

        axisX.setLabelsFont(labelFont)
        axisY.setLabelsFont(labelFont)

        axisPen = QPen(Qt.white)
        axisPen.setWidth(2)

        axisX.setLinePen(axisPen)
        axisY.setLinePen(axisPen)

        axisBrush = QBrush(Qt.white)
        axisX.setLabelsBrush(axisBrush)
        axisY.setLabelsBrush(axisBrush)

        axisX.setRange(0, 30)
        axisX.append("low", 10)
        axisX.append("medium", 20)
        axisX.append("high", 30)

        axisY.setRange(0, 30)
        axisY.append("slow", 10)
        axisY.append("average", 20)
        axisY.append("fast", 30)

        axisX.setGridLineVisible(False)
        axisY.setGridLineVisible(False)

        chart.addAxis(axisX, Qt.AlignBottom)
        chart.addAxis(axisY, Qt.AlignLeft)

        series.attachAxis(axisX)
        series.attachAxis(axisY)

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