def copyAxis(chart: QtCharts.QChart, axis: QtCharts.QAbstractAxis) -> QtCharts.QAbstractAxis: a_copy: QtCharts.QAbstractAxis if axis.type() == QtCharts.QAbstractAxis.AxisTypeBarCategory: a_copy = QtCharts.QBarCategoryAxis(chart) labels = axis.categories() a_copy.append(labels) elif axis.type() == QtCharts.QAbstractAxis.AxisTypeCategory: a_copy = QtCharts.QCategoryAxis(chart) labels = axis.categoriesLabels() a_copy.setStartValue(axis.startValue(labels[0])) a_copy.setLabelsPosition(axis.labelsPosition()) for lab in labels: a_copy.append(lab, axis.endValue(lab)) elif axis.type() == QtCharts.QAbstractAxis.AxisTypeValue: a_copy = QtCharts.QValueAxis(chart) a_copy.setMin(axis.min()) a_copy.setMax(axis.max()) a_copy.setTickCount(axis.tickCount()) a_copy.setMinorTickCount(axis.minorTickCount()) a_copy.setTickInterval(axis.tickInterval()) elif axis.type() == QtCharts.QAbstractAxis.AxisTypeDateTime: a_copy = QtCharts.QDateTimeAxis(chart) a_copy.setMin(axis.min()) a_copy.setMax(axis.max()) a_copy.setFormat(axis.format()) a_copy.setTickCount(axis.tickCount()) else: raise NotImplementedError('Cannot copy axis of type {}'.format( str(axis.type()))) a_copy.setTitleText(axis.titleText()) a_copy.setTitleFont(axis.titleFont()) return a_copy
def __init__(self, frame): self.series = QtCharts.QLineSeries() self.series.setColor(Qt.red) self.axis_x = QtCharts.QDateTimeAxis() # Number of items to display self.axis_x.setTickCount(int(common.SETTINGS["DataCacheSize"])) self.axis_x.setFormat("hh:mm:ss:z") # Date format self.axis_x.setTitleText("Time") self.axis_y = QtCharts.QValueAxis() self.axis_y.setTitleText("Value") self.chart = QtCharts.QChart() self.chart.setTitle("") self.chart.addSeries(self.series) self.chart.addAxis(self.axis_x, QtCore.Qt.AlignBottom) self.chart.addAxis(self.axis_y, QtCore.Qt.AlignLeft) self.series.attachAxis(self.axis_x) self.series.attachAxis(self.axis_y) self.chart_view = QtCharts.QChartView(self.chart) self.layout = QVBoxLayout() self.layout.addWidget(self.chart_view) self.frame = frame self.frame.setLayout(self.layout)
def add_series(self, name, columns): self.series = QtCharts.QLineSeries() self.series.setName(name) for i in range(self.model.rowCount()): t = self.model.index(i, 0).data() date_fmt = "yyyy-MM-dd HH:mm:ss.zzz" x = QDateTime().fromString(t, date_fmt).toSecsSinceEpoch() y = float(self.model.index(i, 1).data()) if x > 0 and y > 0: self.series.append(x, y) self.chart.addSeries(self.series) self.axis_x = QtCharts.QDateTimeAxis() self.axis_x.setTickCount(10) self.axis_x.setFormat("dd.MM (h:mm)") self.axis_x.setTitleText("Date") self.chart.addAxis(self.axis_x, Qt.AlignBottom) self.series.attachAxis(self.axis_x) self.axis_y = QtCharts.QValueAxis() self.axis_y.setTickCount(10) self.axis_y.setLabelFormat("%.2f") self.axis_y.setTitleText("Magnitude") self.chart.addAxis(self.axis_y, Qt.AlignLeft) self.series.attachAxis(self.axis_y) self.model.color = "{}".format(self.series.pen().color().name()) print(self.model.color)
def __init__(self, parent=None): QWidget.__init__(self, parent) self.series = QtCharts.QLineSeries() self.series.setName("Karma points") self.task_list = None self.max_bound: datetime = datetime.datetime.now() self.interval = 7 self.karma_point = 0 self.chart = QtCharts.QChart() self.chart.legend().setVisible(True) self.chart.legend().setAlignment(Qt.AlignBottom) self.chart.addSeries(self.series) self.chart.setTitle("Karma Points") self.chart.setAnimationOptions(QtCharts.QChart.SeriesAnimations) self.axisX = QtCharts.QDateTimeAxis() self.axisX.setFormat("dd MMM") self.axisX.setTickCount(self.interval) self.axisY = QtCharts.QValueAxis() self.chart.setAxisX(self.axisX, self.series) self.chart.setAxisY(self.axisY, self.series) self.chartView = QtCharts.QChartView(self.chart) self.chartView.setRenderHint(QPainter.Antialiasing) self.main_layout = QVBoxLayout(self) self.main_layout.addWidget(self.chartView) self.setLayout(self.main_layout) self.setFixedSize(651, 421)
def plotMeterLvl(self, legendSelection): chart = QtCharts.QChart() lineSeries = QtCharts.QLineSeries() for entry in self.plotData['Zählerstände'][legendSelection]: lineSeries.append(entry['date'].toMSecsSinceEpoch(), entry['level']) chart.addSeries(lineSeries) titleFont = QFont("Sans Serif") titleFont.setPointSize(16) titleFont.setBold(True) chart.setTitleFont(titleFont) chart.setTitle("Zählerstände: " + legendSelection) axisX = QtCharts.QDateTimeAxis() tickCount = min( [12, len(self.plotData['Zählerstände'][legendSelection])]) axisX.setTickCount(tickCount) axisX.setFormat("MM/yy") # axisX.setFormat("MMM yyyy") axisX.setTitleText("Ablesedatum") chart.setAxisX(axisX, lineSeries) # chart.addAxis(axisX, Qt.AlignBottom) # lineSeries.attachAxis(axisX) # axisX.setRange(self.plotDataTags[0], self.plotDataTags[-1]) axisY = QtCharts.QValueAxis() axisY.setLabelFormat("%i") if legendSelection == 'Strom': axisY.setTitleText("Stromzählerstand [kWh]") elif legendSelection == 'Gas': axisY.setTitleText("Gaszählerstand [m<sup>3</sup>]") elif legendSelection == 'Wasser': axisY.setTitleText("Wasserzählerstand [m<sup>3</sup>]") # if minVal < 0: # self.setYRange(maxVal, axisY, minVal) # else: # self.setYRange(maxVal, axisY) chart.setAxisY(axisY, lineSeries) # chart.addAxis(axisY, Qt.AlignLeft) # lineSeries.attachAxis(axisY) # axisY.setRange(0, 20) chart.legend().setVisible(False) # chart.legend().setAlignment(Qt.AlignRight) self.setChart(chart) self.setRenderHint(QPainter.Antialiasing) # draw the plot from scratch (if that makes a difference) print('Meter bar plot drawn')
def __createTimeAxis(self, timeSeries: pd.Series, timeType: Type) -> QtCharts.QAbstractAxis: """ Creates a time axis showing 'timeSeries' values of specified type (Ordinal or Datetime) """ if timeType == Types.Datetime: # Time axis is Datetime xAxis = QtCharts.QDateTimeAxis() xAxis.setFormat(self.settingsPanel.timeAxisFormatCB.currentText()) else: # Time axis is Ordinal (time are str labels) xAxis = QtCharts.QCategoryAxis() for cat, code in zip(timeSeries, timeSeries.cat.codes): xAxis.append(cat, code) xAxis.setStartValue(0) xAxis.setLabelsPosition( QtCharts.QCategoryAxis.AxisLabelsPositionOnValue) xAxis.setTitleText('Time') return xAxis
def __init__(self, items, maxItems=50 * 30, updateInterval=0.1): super().__init__() self.maxItems = maxItems self.timeAxis = None self._next_update = 0 self.updateInterval = updateInterval self.updateTask = make_done_future() self._caches = [] for axis in items.items(): data = [("timestamp", "f8")] for d in axis[1]: if d is None: self._caches.append(TimeCache(maxItems, data)) data = [("timestamp", "f8")] else: data.append((d, "f8")) self._addSerie(d, axis[0]) self._caches.append(TimeCache(maxItems, data)) # Caveat emptor, the order here is important. Hard to find, but the order in # which chart, axis and series are constructed and attached should always be: # - construct Axis, Chart, Serie # - addAxis to chart # - attach series to axis # Changing the order will result in undetermined behaviour, most # likely the axis or even graph not shown. It's irrelevant when you # fill series with data. See QtChart::createDefaultAxes in QtChart # source code for details. self.timeAxis = QtCharts.QDateTimeAxis() self.timeAxis.setReverse(True) self.timeAxis.setTickCount(5) self.timeAxis.setFormat("h:mm:ss.zzz") self.timeAxis.setTitleText("Time (TAI)") self.timeAxis.setGridLineVisible(True) self.addAxis(self.timeAxis, Qt.AlignBottom) for serie in self.series(): serie.attachAxis(self.timeAxis)
def add_series(self, name, columns): ''' Adding the data to the series, you can modify the axis to properly display the QDateTime on the X-axis, and the magnitude values on the Y-axis. ''' # Create QLineSeries self.series = QtCharts.QLineSeries() self.series.setName(name) # Filling QLineSeries for i in range(self.model.rowCount()): # Getting the data t = self.model.index(i, 0).data() date_fmt = "yyyy-MM-dd HH:mm:ss.zzz" x = QDateTime().fromString(t, date_fmt).toSecsSinceEpoch() y = float(self.model.index(i, 1).data()) if x > 0 and y > 0: self.series.append(x, y) self.chart.addSeries(self.series) # Setting X-axis self.axis_x = QtCharts.QDateTimeAxis() self.axis_x.setTickCount(10) self.axis_x.setFormat("dd.MM (h:mm)") self.axis_x.setTitleText("Date") self.chart.addAxis(self.axis_x, Qt.AlignBottom) self.series.attachAxis(self.axis_x) # Setting Y-axis self.axis_y = QtCharts.QValueAxis() self.axis_y.setTickCount(10) self.axis_y.setLabelFormat("%.2f") self.axis_y.setTitleText("Magnitude") self.chart.addAxis(self.axis_y, Qt.AlignLeft) self.series.attachAxis(self.axis_y) # Getting the color from the QChart to use it on the QTableView self.model.color = "{}".format(self.series.pen().color().name())
def __init__(self, can_connection): super().__init__() self._messages = [] layout = QtWidgets.QVBoxLayout() self.chart_view = QtCharts.QChartView() layout.addWidget(self.chart_view) self.setLayout(layout) # Construct graph: self.chart = QtCharts.QChart() self.chart_view.setChart(self.chart) self.busload_series = QtCharts.QLineSeries() self.busload_series.setName("Busload") pen = QtGui.QPen(Qt.red) pen.setWidth(3) self.busload_series.setPen(pen) self.chart.addSeries(self.busload_series) self.load_axis = QtCharts.QValueAxis() self.load_axis.setRange(0, 100000) self.load_axis.setTickCount(6) self.load_axis.setTitleText("Load") self.chart.setAxisY(self.load_axis, self.busload_series) self.time_axis = QtCharts.QDateTimeAxis() self.time_axis.setTitleText("Time") self.time_axis.setFormat("HH:mm:ss.zzz") self.time_axis.setTickCount(5) now = QtCore.QDateTime.currentDateTime() self.time_axis.setRange(now.addMSecs(-100), now.addMSecs(100)) self.chart.setAxisX(self.time_axis, self.busload_series) self._prev_time = now self.timer = QtCore.QTimer() self.timer.timeout.connect(self.on_timer) self.timer.start(500) can_connection.message_received.connect(self.on_message)
def update_chart(self, data, init=False): self.coins_sum += data[1] MStime_now = float(QDateTime.currentDateTime().toMSecsSinceEpoch()) if init: self.series.append(MStime_now, self.coins_sum) for i in range(6): if i and not i % 2: self.series.append(MStime_now + (i * 1), self.coins_sum) else: self.series.append(MStime_now + (i * 1), 0.00000001) else: self.series.append(MStime_now, self.coins_sum) chart = QtCharts.QChart() chart.addSeries(self.series) if not init: chart.setAnimationOptions(QtCharts.QChart.SeriesAnimations) chart.setTitle('Progress') axisX = QtCharts.QDateTimeAxis() axisX.setTickCount(5) axisX.setFormat('HH:mm:ss') axisX.setTitleText('time') chart.addAxis(axisX, Qt.AlignBottom) self.series.attachAxis(axisX) axisY = QtCharts.QValueAxis() axisY.setTickCount(5) axisY.setLabelFormat('%.8f') axisY.setTitleText('coins') chart.addAxis(axisY, Qt.AlignLeft) self.series.attachAxis(axisY) self.chart_view.setChart(chart)
def add_series(self, name, columns): # Create QLineSeries. self.series = QtCharts.QLineSeries() self.series.setName(name) # Fill QLineSeries. for i in range(self.model.rowCount()): # Get the data. t = self.model.index(i, 0).data() date_fmt = 'yyyy-MM-dd HH:mm:ss.zzz' x = QDateTime().fromString(t, date_fmt).toSecsSinceEpoch() y = float(self.model.index(i, 1).data()) if x > 0 and y > 0: self.series.append(x, y) self.chart.addSeries(self.series) # Set X-axis. self.axis_x = QtCharts.QDateTimeAxis() self.axis_x.setTickCount(10) self.axis_x.setFormat('dd.MM (h:mm)') self.axis_x.setTitleText('Date') self.chart.addAxis(self.axis_x, Qt.AlignBottom) self.series.attachAxis(self.axis_x) # Set Y-axis. self.axis_y = QtCharts.QValueAxis() self.axis_y.setTickCount(10) self.axis_y.setLabelFormat('%.2f') self.axis_y.setTitleText('Magnitude') self.chart.addAxis(self.axis_y, Qt.AlignLeft) self.series.attachAxis(self.axis_y) # Get the color from the QChart to use it on the QTableView. self.model.color = '{}'.format(self.series.pen().color().name())
def createSplineChart(data): chart = QtCharts.QChart() # chart.legend().hide() chart.setTitle("Spline chart (market shares)") axisX = QtCharts.QDateTimeAxis() # axisX.setTickCount(10); axisX.setFormat("MM-yyyy") #axisX.setFormat("yyyy/MM/dd hh:mm:ss:zzz"); #axisX.setFormat("hh:mm:ss:zzz"); axisX.setTitleText("Time") chart.addAxis(axisX, Qt.AlignBottom) axisY = QtCharts.QValueAxis() # axisY.setLabelFormat("%.2f"); axisY.setTitleText("%") chart.addAxis(axisY, Qt.AlignLeft) # chart.axes(Qt.Vertical)[0].setRange(0, 100) chart.axes(Qt.Vertical)[0].setRange(0, 3) # seriesFilter = [0, 3, 4, 6] # seriesFilter = [0] # seriesFilter = [3, 4, 6, 7, 9, 10] seriesFilter = [3, 4] valuesToDraw = [data[1][i] for i in seriesFilter] namesToDraw = [data[2][i] for i in seriesFilter] for i in range(len(seriesFilter)): values = valuesToDraw[i] name = namesToDraw[i] series = QtCharts.QSplineSeries() series.setName(name) c1 = PySide2.QtWidgets.QColorDialog.getColor( options=PySide2.QtWidgets.QColorDialog.DontUseNativeDialog) series.setColor(c1) n = len(values) # print(values) # конвертируем столбец time в float, чтобы можно было использовать его как значения оси x for j in range(n): # print(x) time = data[0][j] series.append(float(time.toMSecsSinceEpoch()), values[j]) chart.addSeries(series) series.attachAxis(axisX) series.attachAxis(axisY) # chart.createDefaultAxes() chartView = QtCharts.QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) return chartView
def __init__(self): QWidget.__init__(self) self.ip = default_psu_ip self.channel = 1 layout_final = QVBoxLayout() #left top: ip text = QLabel("IPv4 Address:", self) text.setAlignment(Qt.AlignCenter) self.ip_input = QLineEdit(self.ip, self) top = QHBoxLayout() top.addWidget(text) top.addWidget(self.ip_input) #left bottom: channel text = QLabel("Channel:", self) self.channel_input = QLineEdit("{0}".format(self.channel), self) bottom = QHBoxLayout() bottom.addWidget(text) bottom.addWidget(self.channel_input) left = QVBoxLayout() left.addLayout(top) left.addLayout(bottom) #right: connect checkbox self.checkbox = QCheckBox("connect", self) layout = QHBoxLayout() layout.addLayout(left) layout.addWidget(self.checkbox) layout_final.addLayout(layout) #layout: Name text = QLabel("Name:", self) text.setAlignment(Qt.AlignRight) self.name = QLabel("", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.name) layout_final.addLayout(layout) #layout: Time text = QLabel("Time:", self) text.setAlignment(Qt.AlignRight) self.time = QLabel("", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.time) layout_final.addLayout(layout) #layout: target voltage text = QLabel("Target Voltage (V):", self) self.target_voltage_input = QLineEdit("", self) self.target_voltage_output = QLabel("", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.target_voltage_input) layout.addWidget(self.target_voltage_output) layout_final.addLayout(layout) #layout: output voltage text = QLabel("Output Voltage (V):", self) self.output_voltage = QLabel("", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.output_voltage) layout_final.addLayout(layout) #layout: current limit text = QLabel("Current Limit (mA):", self) self.current_limit_input = QLineEdit("", self) self.current_limit_output = QLabel("", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.current_limit_input) layout.addWidget(self.current_limit_output) layout_final.addLayout(layout) #layout: output current text = QLabel("Output Current (mA):", self) self.output_current = QLabel("", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.output_current) layout_final.addLayout(layout) #layout: switch output self.switch_input = QPushButton("Switch Output", self) self.switch_output = QLabel("", self) layout = QHBoxLayout() layout.addWidget(self.switch_input) layout.addWidget(self.switch_output) layout_final.addLayout(layout) #layout: ChartView chartView = QtCharts.QChartView() layout_final.addWidget(chartView) self.setLayout(layout_final) #signal and slot self.ip_input.returnPressed.connect(self.update_ip) self.channel_input.returnPressed.connect(self.update_channel) self.checkbox.stateChanged.connect(self.connect) self.target_voltage_input.returnPressed.connect( self.set_target_voltage) self.current_limit_input.returnPressed.connect(self.set_current_limit) self.switch_input.clicked.connect(self.toggle_switch) #Timer self.timer = QTimer(self) self.timer.timeout.connect(self.update_data) #Line Chart self.series_voltage = QtCharts.QLineSeries() self.series_current = QtCharts.QLineSeries() chart = QtCharts.QChart() chart.addSeries(self.series_voltage) chart.addSeries(self.series_current) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignTop) markers = chart.legend().markers() markers[0].setLabel("Output Voltage") markers[1].setLabel("Output Current") #chart.setTitle("") self.axisX = QtCharts.QDateTimeAxis() self.axisX.setTickCount(5) self.axisX.setFormat("hh:mm:ss") self.axisX.setTitleText("Time") self.axisX.setMin(QDateTime().currentDateTime().addSecs(-60)) self.axisX.setMax(QDateTime().currentDateTime()) chart.addAxis(self.axisX, Qt.AlignBottom) self.series_voltage.attachAxis(self.axisX) self.series_current.attachAxis(self.axisX) axisY_voltage = QtCharts.QValueAxis() axisY_voltage.setTickCount(8) axisY_voltage.setLabelFormat("%.3f") axisY_voltage.setTitleText("Output Voltage (V)") axisY_voltage.setRange(0, 14) chart.addAxis(axisY_voltage, Qt.AlignLeft) self.series_voltage.attachAxis(axisY_voltage) axisY_current = QtCharts.QValueAxis() axisY_current.setTickCount(8) axisY_current.setLabelFormat("%i") axisY_current.setTitleText("Output Current (mA)") axisY_current.setRange(0, 700) chart.addAxis(axisY_current, Qt.AlignRight) self.series_current.attachAxis(axisY_current) chartView.setChart(chart) chartView.setRenderHint(QPainter.Antialiasing)
def plotMeterAvg(self, legendSelection): origEndIdx = legendSelection.find(':') category = legendSelection[0:origEndIdx] yearly = legendSelection[origEndIdx + 2:origEndIdx + 3] == "J" if len(self.plotData['Zählerstände'][category]) < 2: return avgLevelData = [] # compute average data lastDate = None lastLevel = None for entry in self.plotData['Zählerstände'][category]: date = entry['date'] level = entry['level'] if lastDate is None: lastDate = date lastLevel = level else: dayDiff = lastDate.daysTo(date) if yearly: averageFactor = dayDiff / 365.25 else: averageFactor = dayDiff / 30.44 averageLevel = (level - lastLevel) / averageFactor avgLevelData.append({'date': lastDate, 'level': averageLevel}) lastDate = date lastLevel = level chart = QtCharts.QChart() lineSeries = QtCharts.QLineSeries() for entry in avgLevelData: lineSeries.append(entry['date'].toMSecsSinceEpoch(), entry['level']) chart.addSeries(lineSeries) titleFont = QFont("Sans Serif") titleFont.setPointSize(16) titleFont.setBold(True) chart.setTitleFont(titleFont) if yearly: chart.setTitle("Jährlicher Verbrauch: " + category) else: chart.setTitle("Monatlicher Verbrauch: " + category) axisX = QtCharts.QDateTimeAxis() tickCount = min([12, len(avgLevelData)]) axisX.setTickCount(tickCount) axisX.setFormat("MM/yy") # axisX.setFormat("MMM yyyy") axisX.setTitleText("Ablesedatum") chart.setAxisX(axisX, lineSeries) # chart.addAxis(axisX, Qt.AlignBottom) # lineSeries.attachAxis(axisX) # axisX.setRange(self.plotDataTags[0], self.plotDataTags[-1]) axisY = QtCharts.QValueAxis() axisY.setLabelFormat("%i") if category == 'Strom': axisY.setTitleText("Stromverbrauch [kWh]") elif category == 'Gas': axisY.setTitleText("Gasverbrauch [m<sup>3</sup>]") elif category == 'Wasser': axisY.setTitleText("Wasserverbrauch [m<sup>3</sup>]") # if minVal < 0: # self.setYRange(maxVal, axisY, minVal) # else: # self.setYRange(maxVal, axisY) chart.setAxisY(axisY, lineSeries) # chart.addAxis(axisY, Qt.AlignLeft) # lineSeries.attachAxis(axisY) # axisY.setRange(0, 20) chart.legend().setVisible(False) # chart.legend().setAlignment(Qt.AlignRight) self.setChart(chart) self.setRenderHint(QPainter.Antialiasing) # draw the plot from scratch (if that makes a difference) print('Meter bar plot drawn')