def show_diagram(self): self.student_diagram_ui.label_4.setText(self.label_2.text()) self.student_diagram_ui.label_7.setText(self.label_8.text()) self.student_diagram_ui.label_8.setText(self.label_6.text()) self.student_diagram_ui.label_10.setText(self.label_4.text()) max_value = 0 series = QBarSeries() for i in self.result: set0 = QBarSet(i[0]) set0.append(float(i[1])) series.append(set0) if max_value < (float(i[1])): max_value = float(i[1]) axisY = QValueAxis() axisY.setRange(0, max_value) chart = QChart() series.attachAxis(axisY) chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) centralwidget = self.student_diagram_ui.centralwidget self.student_diagram_ui.chartview = QChartView(chart, centralwidget) self.student_diagram_ui.chartview.setGeometry(QtCore.QRect(10, 110, 880, 371)) self.student_diagram_ui.pushButton_3.show() self.student_diagram_ui.update(self.dark_theme) self.student_diagram_window.show()
def createLineChart(self): chart = QChart() chart.setTitle("像素分布直方图") seriesArray = [] # for i, data_list in enumerate(self.m_dataTable): # series = QLineSeries() # for value, _ in data_list: # series.append(value) # series.setName("Series " + str(i)) # seriesArray.append(series) # chart.addSeries(series) axisX = QValueAxis() axisY = QValueAxis() axisX.setRange(0, 255) axisY.setRange(0, 50000) chart.setAxisX(axisX) chart.setAxisY(axisY) # for i in seriesArray: # chart.removeSeries(i) return chart
def __init__(self, parent): super(ScoresWindow, self).__init__(parent) self.parent = parent mainLayout = QBoxLayout(QBoxLayout.TopToBottom) columnLayout = QBoxLayout(QBoxLayout.LeftToRight) column = [QBoxLayout(QBoxLayout.TopToBottom) for i in range(3)] for i in column: columnLayout.addLayout(i) self.cell = [QLabel() for i in range(9)] for i in range(9): column[i//3].addWidget(self.cell[i]) chartView = QChartView() axisY = QValueAxis() axisY.setRange(-700,700) axisY.setLabelFormat("%d") self.chart = LineChart(((10,20,30,40,50,60,70,80),(0,-10,-20,-30,-40,50,-20,0))) self.chart.addAxis(axisY, Qt.AlignLeft) for i in self.chart.series: i.attachAxis(axisY) chartView.setChart(self.chart) self.level = QLabel() mainLayout.addLayout(columnLayout) mainLayout.addWidget(chartView) self.setLayout(mainLayout) self.setFixedSize(300,400) self.setModal(True) self.setStrings()
def bargraph(self): ''' Processes and Creates Bar Graph. ''' self.barchart = self.findChild(QChartView, "attackgraph") bardata = self.data.getBar() chartobj = Barchart(bardata) chartseries = chartobj.getSeries() # create QChart object and add data chart = QChart() chart.addSeries(chartseries) chart.setTitle("Attacks Over the Past 12 Months") chart.setAnimationOptions(QChart.SeriesAnimations) axisX = QBarCategoryAxis() axisX.append(chartobj.getKeys()) chart.addAxis(axisX, Qt.AlignBottom) axisY = QValueAxis() axisY.setRange(0, chartobj.getMax()) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(False) self.barchart.setChart(chart)
def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Demo12_1, QChart 基本绘图") self.resize(580, 420) chart = QChart() chart.setTitle("简单函数曲线") chartView = QChartView(self) chartView.setChart(chart) self.setCentralWidget(chartView) series0 = QLineSeries() series1 = QLineSeries() series0.setName("sin曲线") series1.setName("cos曲线") chart.addSeries(series0) chart.addSeries(series1) t = 0 intv = 0.1 pointCount = 100 for i in range(pointCount): y1 = math.cos(t) series0.append(t, y1) y2 = 1.5 * math.sin(t + 20) series1.append(t, y2) t = t + intv axisX = QValueAxis() axisX.setRange(0, 10) axisX.setTitleText("time(secs)") axisY = QValueAxis() axisY.setRange(-2, 2) axisY.setTitleText("value") chart.setAxisX(axisX, series0) chart.setAxisY(axisY, series0) chart.setAxisX(axisX, series1) chart.setAxisY(axisY, series1)
def _init_chart(self) -> None: series = QBarSeries() axis_x = QBarCategoryAxis() axis_y = QValueAxis() data_set = defaultdict(int) for title, money in self.base: data_set[title] += money for title, money in data_set.items(): bar = QBarSet(title) axis_x.append(title) bar.append(money) series.append(bar) # self.chart = QChart() self.chart.addSeries(series) self.chart.setAnimationOptions(QChart.SeriesAnimations) # series.attachAxis(axis_x) self.chart.addAxis(axis_x, Qt.AlignBottom) axis_y.setRange(0, max(data_set.values())) axis_y.setTickCount(11) self.chart.addAxis(axis_y, Qt.AlignLeft) series.attachAxis(axis_y) # self.chart.legend().setVisible(True) self.chart.legend().setAlignment(Qt.AlignBottom)
def setAxisRange(self, min, max): axisY = QValueAxis() axisY.setRange(min, max) axisY.setLabelFormat(" ") self.addAxis(axisY, Qt.AlignLeft) for s in self.series: s.attachAxis(axisY)
def create_barchart(self, series, max_val, animation=True): if animation: animation_type = QChart.AllAnimations else: animation_type = QChart.NoAnimation chart = QChart() chart.addSeries(series) chart.setBackgroundVisible(False) chart.setMargins(QMargins()) chart.setAnimationOptions(animation_type) labels = ('Human', 'Bot') axisX = QBarCategoryAxis() axisX.append(labels) axisY = QValueAxis() axisY.setTitleText("Percentage (%)") axisY.setRange(0, max_val) chart.addAxis(axisX, Qt.AlignBottom) chart.addAxis(axisY, Qt.AlignLeft) font = QFont() font.setPointSize(9) chart.legend().setVisible(True) chart.legend().setFont(font) chart.legend().setAlignment(Qt.AlignBottom) self.ui.barchart.setChart(chart) self.ui.barchart.setRenderHint(QPainter.Antialiasing)
def initChart(self, xAxis): self._chart = QChart() #调整边距 self._chart.layout().setContentsMargins(0, 0, 0, 0) #外界 self._chart.setMargins(QMargins(3, 0, 3, 0)) #内界 self._chart.setBackgroundRoundness(0) self._chart.setBackgroundVisible(False) #设置主题 self._chart.setTheme(QChart.ChartThemeBlueIcy) # 抗锯齿 self.setRenderHint(QPainter.Antialiasing) # 开启动画效果 self._chart.setAnimationOptions(QChart.SeriesAnimations) self.categories = xAxis self._series = QPercentBarSeries(self._chart) self._chart.addSeries(self._series) axis_x = QBarCategoryAxis(self._chart) axis_x.append(self.categories) axis_x.setLabelsAngle(280) axis_y = QValueAxis(self._chart) axis_y.setTitleText("比例") axis_y.setRange(0, 100) self._chart.addAxis(axis_x, Qt.AlignBottom) self._chart.addAxis(axis_y, Qt.AlignLeft) self._series.attachAxis(axis_x) self._series.attachAxis(axis_y) self.setChart(self._chart)
def __init__(self, predictions, probabilities): # calls the parent (QMainWindow) constructor super().__init__() # Size of the window self.resize(800, 600) # The title of the window self.setWindowTitle("Flower Confidence score graph") # The array to hold flower sets self.flowerSets = [] # A Q bar series object self.flowerSeries = QBarSeries() # The for loop add Q bar sets and probabilities to the Q bsr series object. for i in range(5): self.flowerSets.append( QBarSet(predictions[i] + " ({0:.3f}%)".format(probabilities[i]))) self.flowerSets[i].append(probabilities[i]) self.flowerSeries.append(self.flowerSets[i]) # creates the char that will be the bar graph chart (also the base class of all qt charts) flowerChart = QChart() # added the series object to the chart object flowerChart.addSeries(self.flowerSeries) # Adds a title to the graph flowerChart.setTitle('Confidence score percentages by flower type') # Gives the graph a nice animation when opened flowerChart.setAnimationOptions(QChart.SeriesAnimations) # The next two line label the x axis axisX = QBarCategoryAxis() axisX.append(["Flower Types"]) # Gives the y axis its values axisY = QValueAxis() axisY.setRange(0, probabilities[0]) # added the axises to the chart flowerChart.addAxis(axisX, Qt.AlignBottom) flowerChart.addAxis(axisY, Qt.AlignLeft) # Makes sure teh legend is visible flowerChart.legend().setVisible(True) # Places the legend to the bottom of the chart flowerChart.legend().setAlignment(Qt.AlignBottom) # places the chart in a chart view flowerChartView = QChartView(flowerChart) # Adds the chart to the main widget self.setCentralWidget(flowerChartView)
def build(self): self.setWindowTitle("Histogram - " + self.name) self.setMinimumSize(400, 300) # Close when ctrl+w is triggered QShortcut(QKeySequence("Ctrl+W"), self, self.close) # 2D array -> 1D array img = self.image.ravel() # Process histogram histogram, bin_edges = np.histogram(img, bins='auto') bar_series = QBarSeries() bar_ = QBarSet("") # Append values for val in histogram: bar_.append(val) pen = bar_.pen() pen.setColor(Qt.black) pen.setWidth(0.1) bar_.setPen(pen) # Append bar to the bar series bar_series.append(bar_) # Chart object chart = QChart() chart.addSeries(bar_series) # Active animation chart.setAnimationOptions(QChart.SeriesAnimations) # Do not show title chart.legend().setVisible(False) # Draw Axes, with [min, max] # Y axis h_max = histogram.max() axis_y = QValueAxis() axis_y.setRange(0, h_max) # X axis be_max = bin_edges.max() be_min = bin_edges.min() axis_x = QValueAxis() axis_x.setRange(be_min, be_max) # Add axis to chart + rendering chart.addAxis(axis_x, Qt.AlignBottom) chart.addAxis(axis_y, Qt.AlignLeft) view = QChartView(chart) view.setRenderHint(QPainter.Antialiasing) self.setCentralWidget(view)
def createBar(self): min_num, max_num = 0, 100 linked_bag_list = [] try: df = self.linked['Beam Diff'].dropna() linked_bag_list = df.values.tolist() min_num = int(min(linked_bag_list)) if min_num > 0: # check if greater than 0, set to 0 min_num = 0 max_num = int(max(linked_bag_list)) except AttributeError: self.statusbar.showMessage('Data not ready') count = [0] * (max_num + 1) # choose the largest num as length of count for num in linked_bag_list: count[int(num)] += 1 # update every number's count max_count = max(count) setBar = QBarSet('Beam Difference Occurrence') setBar.append(count) brush = QBrush(QColor(0x57B1FD)) pen = QPen(QColor(0x57B1FD)) pen.setWidth(2) setBar.setPen(pen) setBar.setBrush(brush) series = QBarSeries() series.append(setBar) chart = QChart() chart.setTheme(QChart.ChartThemeBlueIcy) font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.setTitle('Linked Bins Histogram') chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) axisX = QValueAxis() axisX.setTitleText("Attenuation Window") axisX.setRange(min_num, max_num+20) chart.setAxisX(axisX, series) axisY = QValueAxis() axisY.setTitleText("Frequency") axisY.setRange(0, max_count+20) chart.setAxisY(axisY, series) chart.legend().hide() chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) return chartView
def __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)
def load_glycation(self, filename: Optional[str] = None) -> None: """ Load glycation data from a CSV file and display it in the corresponding chart view. :param str filename: directly load this file :return: nothing, sets self.se_glycation :rtype: None """ # load and clean glycation data if filename is None: filename, self.last_path = get_filename( self, "open", self.tr("Load glycation data ..."), self.last_path, FileTypes(["csv"])) if filename is None: return logging.info( self.tr("Loading glycation data in '{}'").format(filename)) try: self.glycation = read_clean_datasets(filename) except (OSError, ValueError) as e: logging.error(str(e)) QMessageBox.critical(self, self.tr("Error"), str(e)) return # extract x- and y-values from series x_values = [str(i) for i in self.glycation.index] y_values = [a.nominal_value for a in self.glycation] # assemble the chart bar_set = QBarSet("glycation abundance") bar_set.append(y_values) bar_set.setColor(QColor("#a1dab4")) bar_set.hovered.connect(self.update_glycation_label) bar_series = QBarSeries() bar_series.append(bar_set) x_axis = QBarCategoryAxis() x_axis.append(x_values) x_axis.setTitleText(self.tr("count")) y_axis = QValueAxis() y_axis.setRange(0, 100) y_axis.setTitleText(self.tr("abundance")) y_axis.setLabelFormat("%d") chart = QChart() chart.addSeries(bar_series) chart.setAxisX(x_axis, bar_series) chart.setAxisY(y_axis, bar_series) chart.legend().setVisible(False) chart.setBackgroundRoundness(0) chart.layout().setContentsMargins(0, 0, 0, 0) chart.setMargins(QMargins(5, 5, 5, 5)) self.cvGlycation.setChart(chart)
def plot_candlechart(ohlc_data): app = ParaMakerApplication([]) #app.setStyleSheet("background-color:black;") series = QCandlestickSeries() series.setBodyOutlineVisible(False) series.setDecreasingColor(Qt.red) series.setIncreasingColor(Qt.green) rsi = qc.QLineSeries() # 5-days average data line rsi.append(QPointF(ohlc_data[300].timestamp, ohlc_data[300].closed)) rsi.append(QPointF(ohlc_data[700].timestamp, ohlc_data[700].closed)) #rsi.append(QPointF(ohlc_data[150].timestamp, ohlc_data[100].closed)) tm = [] # stores str type data # in a loop, series and rsi append corresponding data for candle in ohlc_data: series.append( QCandlestickSet(candle.opened, candle.high, candle.low, candle.closed)) #rsi.append(QPointF(num, m)) tm.append(str(candle.timestamp)) #rsi.append(str(candle.timestamp)) #rsi_values = calculate_rsi(14, ohlc_data) chart = QChart() chart.setBackgroundVisible(False) chart.setPlotAreaBackgroundVisible(False) chart.addSeries(series) # candle chart.addSeries(rsi) # rsi line #chart.axisX(rsi).setRange(ohlc_data[0].timestamp, ohlc_data[-1].timestamp) chart.createDefaultAxes() axisXRSI = QValueAxis() axisYRSI = QValueAxis() axisXRSI.setRange(ohlc_data[0].timestamp, ohlc_data[-1].timestamp) axisYRSI.setRange(ohlc_data[0].closed, ohlc_data[-1].closed) axisXRSI.setGridLineVisible(False) axisYRSI.setGridLineVisible(False) chart.setAxisX(axisXRSI, rsi) chart.setAxisY(axisYRSI, rsi) chart.legend().hide() chart.axisX(series).setCategories(tm) #chart.axisX(series).setGridLineVisible(False) #chart.axisY(series).setGridLineVisible(False) ###chart.axisX(rsi).setVisible(False) chartview = QChartView(chart) chartview.setRenderHint(QPainter.Antialiasing) ui = ParaMakerWindow() ui.setCentralWidget(chartview) sys.exit(app.exec_())
def set_x_aix(self, years: []) -> QValueAxis: # x轴坐标——年份 x_aix = QValueAxis() x_aix.setRange(years[0], years[-1]) x_aix.setLabelFormat('%d') x_aix.setGridLineVisible(True) x_aix.setTickCount(len(years)) x_aix.setMinorTickCount(5) # 每两个月一个小分级 return x_aix
def beforeDelay(self): print("in before delay bar") min_num, max_num = 0, 100 max_count = 0 total_stopped_time = [] try: total_stopped_time = self.tm.total_stopped_time max_num = max(total_stopped_time) except AttributeError: self.statusbar.showMessage('Data not ready') count = total_stopped_time count = [0] * (int(max_num) + 1 ) # choose the largest num as length of count for num in total_stopped_time: count[int(num)] += 1 # update every number's count max_count = max(count) print(len(total_stopped_time), max_count) setBar = QBarSet('stop time') setBar.append(count) brush = QBrush(QColor(0x57B1FD)) pen = QPen(QColor(0x57B1FD)) pen.setWidth(2) setBar.setPen(pen) setBar.setBrush(brush) series = QBarSeries() series.append(setBar) chart = QChart() font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.setTitle('Stop time Histogram (before)') chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) axisX = QValueAxis() axisX.setRange(min_num, max_num + 20) chart.setAxisX(axisX, series) axisY = QValueAxis() axisY.setRange(0, max_count + 20) chart.setAxisY(axisY, series) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) # MainWindow.setCentralWidget(chartView) return chartView
def afterDelay(self): # print("in after delay bar") min_num, max_num = 0, 100 max_count = 0 total_stopped_after_delay = [] count = [0] * (int(max_num) + 1) # choose the largest num as length of count try: total_stopped_after_delay = self.tm.total_stopped_after_delay max_num = max(total_stopped_after_delay) count = [0] * (int(max_num) + 1) # choose the largest num as length of count for num in total_stopped_after_delay: count[int(num)] += 1 # update every number's count max_count = max(count) except (AttributeError, ValueError): self.statusbar.showMessage('Data not ready') setBar = QBarSet('Stop Time Occurrence') setBar.append(count) brush = QBrush(QColor(0xA6E22E)) # Green pen = QPen(QColor(0xA6E22E)) # Green pen.setWidth(2) setBar.setPen(pen) setBar.setBrush(brush) series = QBarSeries() series.append(setBar) chart = QChart() font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.setTitle('Stop time Occurrence (after)') chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) axisX = QValueAxis() axisX.setRange(min_num, max_num+20) chart.setAxisX(axisX, series) axisY = QValueAxis() axisY.setRange(0, max_count+20) chart.setAxisY(axisY, series) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) # MainWindow.setCentralWidget(chartView) return chartView
def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Demo12_1, QChart基本绘图") self.resize(580, 420) #创建chart和chartView chart = QChart() #创建 Chart chart.setTitle("简单函数曲线") chartView = QChartView(self) #创建 ChartView chartView.setChart(chart) #Chart添加到ChartView self.setCentralWidget(chartView) #创建曲线序列 series0 = QLineSeries() series1 = QLineSeries() series0.setName("Sin曲线") series1.setName("Cos曲线") chart.addSeries(series0) #序列添加到图表 chart.addSeries(series1) #序列添加数值 t = 0 intv = 0.1 pointCount = 100 for i in range(pointCount): y1 = math.cos(t) series0.append(t, y1) y2 = 1.5 * math.sin(t + 20) series1.append(t, y2) t = t + intv ##创建坐标轴 axisX = QValueAxis() #X 轴 axisX.setRange(0, 10) #设置坐标轴范围 axisX.setTitleText("time(secs)") #标题 ## axisX.setLabelFormat("%.1f") #标签格式 ## axisX.setTickCount(11) #主分隔个数 ## axisX.setMinorTickCount(4) ## axisX.setGridLineVisible(false) axisY = QValueAxis() #Y 轴 axisY.setRange(-2, 2) axisY.setTitleText("value") ## axisY.setTickCount(5) ## axisY.setMinorTickCount(4) ## axisY.setLabelFormat("%.2f") #标签格式 ## axisY.setGridLineVisible(false) #为序列设置坐标轴 chart.setAxisX(axisX, series0) #为序列设置坐标轴 chart.setAxisY(axisY, series0) chart.setAxisX(axisX, series1) #为序列设置坐标轴 chart.setAxisY(axisY, series1)
class Window(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("PyQtChart Demo") self.setGeometry(500, 275, 650, 500) self.show() self.createLineChart() def createLineChart(self): self.font = QFont("Arial") self.font.setPixelSize(16) self.font.setBold(True) self.pen = QPen(QColor(0, 153, 0)) self.pen.setWidth(3) self.series = QLineSeries(self) self.series.setPen(self.pen) self.x = np.arange(0, 2 * np.pi, 0.01) for i in self.x: self.series.append(i, np.sin(i)) self.chart = QChart() self.chart.addSeries(self.series) self.chart.setAnimationOptions(QChart.SeriesAnimations) self.chart.setTitleFont(self.font) self.chart.setTitleBrush(QBrush(Qt.blue)) self.chart.setTitle("Line Chart Demo") self.chart.legend().setVisible(True) self.chart.legend().setAlignment(Qt.AlignBottom) self.chartview = QChartView(self.chart) self.chartview.setRenderHint(QPainter.Antialiasing) self.axisX = QValueAxis() self.axisX.setRange(0, 2 * np.pi) self.axisX.setTickCount(6) self.axisX.setLabelFormat("%.1f") self.axisX.setTitleText("x") self.axisY = QValueAxis() self.axisY.setRange(0, 100) self.axisY.setLabelFormat("%d") self.axisY.setTitleText("sin(x)") self.chart.addAxis(self.axisX, Qt.AlignBottom) self.chart.addAxis(self.axisY, Qt.AlignLeft) self.setCentralWidget(self.chartview)
def update_axes(self): # Get and remove all axes for axis in self.chart.axes(): self.chart.removeAxis(axis) # Create new axes # Create axis X # axisX = QDateTimeAxis() # axisX.setTickCount(5) # axisX.setFormat("dd MMM yyyy") # axisX.setTitleText("Date") # self.chart.addAxis(axisX, Qt.AlignBottom) # axisX.rangeChanged.connect(self.axis_range_changed) axisX = QValueAxis() axisX.setTickCount(10) axisX.setLabelFormat("%li") axisX.setTitleText("Seconds") self.chart.addAxis(axisX, Qt.AlignBottom) # axisX.rangeChanged.connect(self.axis_range_changed) # Create axis Y axisY = QValueAxis() axisY.setTickCount(5) axisY.setLabelFormat("%.3f") axisY.setTitleText("Values") self.chart.addAxis(axisY, Qt.AlignLeft) # axisY.rangeChanged.connect(self.axis_range_changed) ymin = None ymax = None # Attach axes to series, find min-max for series in self.chart.series(): series.attachAxis(axisX) series.attachAxis(axisY) vect = series.pointsVector() for i in range(len(vect)): if ymin is None: ymin = vect[i].y() ymax = vect[i].y() else: ymin = min(ymin, vect[i].y()) ymax = max(ymax, vect[i].y()) # Update range # print('min max', ymin, ymax) if ymin is not None: axisY.setRange(ymin, ymax) # Make the X,Y axis more readable axisX.applyNiceNumbers()
def init_series(self, series, label): """ Series settings """ self.chart.setAxisX(self.axis_X, series) axis_Y = QValueAxis() # pylint: disable=invalid-name axis_Y.setLabelFormat("%i") axis_Y.setTitleText(label) axis_Y.setRange(0, 100) self.chart.addAxis(axis_Y, Qt.AlignLeft) self.chart.setAxisY(axis_Y, series)
def agg_glycoforms(self) -> None: """ Display glycoform data in the corresponding chart view. :return: nothing :rtype: None """ # aggregate "other" abundances if self.cbAggGlycoforms.isChecked(): agg_abundance = ( self.glycoforms.iloc[self.sbAggGlycoforms.value():].sum()) self.glycoforms_agg = ( self.glycoforms.iloc[:self.sbAggGlycoforms.value()].append( pd.Series(agg_abundance, index=[self.tr("other")]))) else: self.glycoforms_agg = self.glycoforms # extract x- and y-values from series x_values = [str(i) for i in self.glycoforms_agg.index] y_values = [a.nominal_value for a in self.glycoforms_agg] # assemble the chart bar_set = QBarSet("glycoform abundance") bar_set.append(y_values) bar_set.setColor(QColor("#2c7fb8")) bar_set.hovered.connect(self.update_glycoform_label) bar_series = QBarSeries() bar_series.append(bar_set) x_axis = QBarCategoryAxis() x_axis.append(x_values) x_axis.setTitleVisible(False) x_axis.setLabelsAngle(270) range_max = max(self.glycoforms_agg).nominal_value range_max = math.ceil(range_max / 20) * 20 tick_count = range_max // 20 + 1 y_axis = QValueAxis() y_axis.setRange(0, range_max) y_axis.setTickCount(tick_count) y_axis.setTitleText(self.tr("abundance")) y_axis.setLabelFormat("%d") chart = QChart() chart.addSeries(bar_series) chart.setAxisX(x_axis, bar_series) chart.setAxisY(y_axis, bar_series) chart.legend().setVisible(False) chart.setBackgroundRoundness(0) chart.layout().setContentsMargins(0, 0, 0, 0) chart.setMargins(QMargins(5, 5, 5, 5)) self.cvGlycoforms.setChart(chart)
class Chart(QChartView): def __init__(self, barCount: int): super().__init__() self.chart = QChart() self.setChart(self.chart) self.setRenderHint(QPainter.Antialiasing) self.chart.setAnimationOptions(QChart.SeriesAnimations) self.chart.setBackgroundVisible(True) self.chart.legend().setVisible(False) self.series = QBarSeries() self.chart.addSeries(self.series) self.barValues = QBarSet('') self.series.append(self.barValues) for i in range(barCount): self.barValues << 0. self.xAxis = QBarCategoryAxis() self.chart.addAxis(self.xAxis, Qt.AlignBottom) self.series.attachAxis(self.xAxis) self.xAxis.setTitleText('yPlus ranges') self.yAxis = QValueAxis() self.chart.addAxis(self.yAxis, Qt.AlignLeft) self.series.attachAxis(self.yAxis) self.yAxis.setTitleText('% of surface area') self.yAxis.setRange(0, 100) def setBarRanges(self, pois: List[float]): for i in range(len(pois)): if i == 0: tag = 'lt ' + str(pois[0]) elif i == len(pois) - 1: tag = 'gt ' + str(pois[-1]) else: tag = str(pois[i]) + ' - ' + str(pois[i + 1]) if not self.xAxis.count(): self.xAxis.append(tag) else: self.xAxis.replace(self.xAxis.at(i), tag) def setBarValues(self, values: List[float]): assert len(values) == self.barValues.count() for i in range(len(values)): if not self.barValues.count(): self.barValues.insert(i, 0.) else: self.barValues.replace(i, values[i])
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()
def main(): import sys app = QApplication(sys.argv) set0 = QBarSet("Jane") set1 = QBarSet("John") set2 = QBarSet("Axel") set3 = QBarSet("Mary") set4 = QBarSet("Samantha") set0 << 1 << 2 << 3 << 4 << 5 << 6 set1 << 5 << 0 << 0 << 4 << 0 << 7 set2 << 3 << 5 << 8 << 13 << 8 << 5 set3 << 5 << 6 << 7 << 3 << 4 << 5 set4 << 9 << 7 << 5 << 3 << 1 << 2 series = QBarSeries() series.append(set0) series.append(set1) series.append(set2) series.append(set3) series.append(set4) chart = QChart() chart.addSeries(series) chart.setTitle("Simple barchart example") chart.setAnimationOptions(QChart.SeriesAnimations) categories = ("Jan", "Feb", "Mar", "Apr", "May", "Jun") axisX = QBarCategoryAxis() axisX.append(categories) chart.addAxis(axisX, Qt.AlignBottom) series.attachAxis(axisX) axisY = QValueAxis() axisY.setRange(0, 15) chart.addAxis(axisY, Qt.AlignLeft) series.attachAxis(axisY) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) window = QMainWindow() window.setCentralWidget(chartView) window.resize(420, 300) window.show() sys.exit(app.exec_())
def ageWiseBarGraph(self): self.w = Window2() self.w.show() set0 = QBarSet('below 25') set1 = QBarSet('25 to 35') set2 = QBarSet('36 to 45') set3 = QBarSet('46 to 55') set4 = QBarSet('above 55') file="killings.csv" ageSet = [0,0,0,0,0] with open('killings.csv') as File: csvReader = csv.reader(File) next(csvReader) for row in csvReader: if int(row[5]) < 25: ageSet[0]+=1 elif int(row[5]) >=25 and int(row[5])<= 35: ageSet[1]+=1 elif int(row[5]) >35 and int(row[5])<=45: ageSet[2]+=1 elif int(row[5]) >45 and int(row[5])<= 55: ageSet[3]+=1 else: ageSet[4]+=1 print (ageSet) set0.append(ageSet[0]) set1.append(ageSet[1]) set2.append(ageSet[2]) set3.append(ageSet[3]) set4.append(ageSet[4]) series = QBarSeries() series.append(set0) series.append(set1) series.append(set2) series.append(set3) series.append(set4) chart = QChart() chart.addSeries(series) chart.setTitle('Age wise comparison') chart.setAnimationOptions(QChart.SeriesAnimations) msg = ('Death Toll') axisX = QBarCategoryAxis() axisX.append(msg) axisY = QValueAxis() axisY.setRange(0, 200) chart.addAxis(axisX, Qt.AlignBottom) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) self.w.setCentralWidget(chartView)
def __createChart(self): self.__chart = QChart() self.ui.chartView.setChart(self.__chart) self.__chart.legend().setVisible(False) #隐藏图例 self.__chart.setMargins(QMargins(0, 0, 0, 0)) #把间距设置到最小 #初始化线条数组 series = [QLineSeries() for _ in range(15)] color = [ '#FF88C2', '#FF8888', '#FFA488', '#FFBB66', '#FFDD55', '#FFFF77', '#DDFF77', '#BBFF66', '#66FF66', '#77FFCC', '#77FFEE', '#66FFFF', '#77DDFF', '#99BBFF', '#9999FF' ] #设置线条颜色形状 pen = QPen() pen.setStyle(Qt.SolidLine) pen.setWidth(2) for i in range(15): pen.setColor(QColor(color[i])) series[i].setPen(pen) #向表格添加线条 for i in range(15): self.__chart.addSeries(series[i]) #设置坐标轴 axisX = QValueAxis() #self.__curAxis=axisX #当前坐标轴 axisX.setRange(0, 200) #设置坐标轴范围 axisX.setLabelFormat("%d") #标签格式 axisX.setTickCount(5) #主分隔个数 axisX.setMinorTickCount(4) axisX.setGridLineVisible(True) axisX.setMinorGridLineVisible(False) axisY = QValueAxis() axisY.setRange(0, 1024) axisY.setLabelFormat("%d") #标签格式 axisY.setTickCount(5) axisY.setMinorTickCount(4) axisY.setGridLineVisible(True) axisY.setMinorGridLineVisible(False) self.__chart.addAxis(axisX, Qt.AlignBottom) #坐标轴添加到图表,并指定方向 self.__chart.addAxis(axisY, Qt.AlignLeft) for i in range(15): series[i].attachAxis(axisX) series[i].attachAxis(axisY)
def set_bound(self, dt, low, high): axisX = QDateTimeAxis() axisX.setFormat('h:mm') start_time = QDateTime() finish_time = QDateTime() start_time.setDate(QDate(dt.year, dt.month, dt.day)) start_time.setTime(QTime(9, 0)) finish_time.setDate(QDate(dt.year, dt.month, dt.day)) finish_time.setTime(QTime(15, 30)) axisX.setRange(start_time, finish_time) axisY = QValueAxis() axisY.setRange(low, high) self.chart_view.chart().setAxisX(axisX, self.price_series) self.chart_view.chart().setAxisY(axisY, self.price_series)
class StaticChart(QChart): def __init__(self): super().__init__() self.series_list = [] self.axisX = QValueAxis() self.axisY = QValueAxis() self.axisPen = QPen(PyQt5.QtCore.Qt.red) self.axisPen.setWidth(4) self.axisX.setLinePen(self.axisPen) self.axixBrush = QBrush(PyQt5.QtCore.Qt.green) self.axisX.setLabelsBrush(self.axixBrush) self.axisX.setGridLineVisible(True) self.setAxisX(self.axisX) self.setAxisY(self.axisY) def add_xyseries(self, type=StaticSeries): series = type() self.addSeries(series) series.attachAxis(self.axisX) series.attachAxis(self.axisY) self.series_list.append(series) return series def set_xrange(self, xmin, xmax): self.axisX.setRange(xmin, xmax) def set_yrange(self, ymin, ymax): self.axisY.setRange(ymin, ymax) def autoscale(self): xmax = ymax = float("-inf") xmin = ymin = float("+inf") for s in self.series_list: points = s.pointsVector() for p in points: if p.x() < xmin: xmin = p.x() if p.x() > xmax: xmax = p.x() if p.y() < ymin: ymin = p.y() if p.y() > ymax: ymax = p.y() self.set_xrange(xmin, xmax) self.set_yrange(ymin, ymax)
class View: def __init__( self, _name: str, _wizard: "ParadoxTrading.Chart.Wizard", _adaptive: bool, _view_stretch: int, _chart_stretch: int, _index: int, ): self.name = _name self.wizard = _wizard self.adaptive = _adaptive self.view_stretch = _view_stretch self.chart_stretch = _chart_stretch self.index = _index self.series_table: typing.Dict[str, SeriesAbstract] = {} self.axis_x = QValueAxis() # show x will slow down chart self.axis_x.setVisible(False) self.axis_y = QValueAxis() # set name to axis_y, price for price, volume for volume, etc self.axis_y.setTitleText(self.name) self.begin_y: float = None self.end_y: float = None def addBar( self, _name: str, _x_list: typing.Sequence, _y_list: typing.Sequence, _color: typing.Any = None, _show_value: bool = False, ): assert _name not in self.series_table.keys() self.series_table[_name] = BarSeries( _name, _x_list, _y_list, _color, _show_value ) def addLine( self, _name: str, _x_list: typing.Sequence, _y_list: typing.Sequence, _color: typing.Any = None, _show_value: bool = False, ): assert _name not in self.series_table.keys() self.series_table[_name] = LineSeries( _name, _x_list, _y_list, _color, _show_value ) def addScatter( self, _name: str, _x_list: typing.Sequence, _y_list: typing.Sequence, _color: typing.Any = None, _show_value: bool = False ): assert _name not in self.series_table.keys() self.series_table[_name] = ScatterSeries( _name, _x_list, _y_list, _color, _show_value ) def addCandle( self, _name: str, _x_list: typing.Sequence, _y_list: typing.Sequence[typing.Sequence], _inc_color: typing.Any = None, _dec_color: typing.Any = None, _show_value: bool = False ): assert _name not in self.series_table.keys() self.series_table[_name] = CandleSeries( _name, _x_list, _y_list, _inc_color, _dec_color, _show_value ) def calcSetX(self) -> typing.Set: """ get the set of x, to get x range for wizard :return: the set of all x value """ tmp = set() for v in self.series_table.values(): tmp |= set(v.calcSetX()) return tmp def calcRangeY(self, _begin_x=None, _end_x=None): """ get range of y for this view :return: (min, max) """ tmp_min_list = [] tmp_max_list = [] for v in self.series_table.values(): min_y, max_y = v.calcRangeY(_begin_x, _end_x) if min_y is not None and max_y is not None: tmp_min_list.append(min_y) tmp_max_list.append(max_y) if tmp_min_list: self.begin_y = min(tmp_min_list) if tmp_max_list: self.end_y = max(tmp_max_list) def setAxisX(self, _begin: float, _end: float): self.axis_x.setRange(_begin, _end) def setAxisY(self, _begin: float, _end: float): self.axis_y.setRange(_begin, _end) def createChartView( self, _x2idx: dict, _idx2x: list ) -> QHBoxLayout: chart = QChart() # assign y range self.calcRangeY() self.setAxisY(self.begin_y, self.end_y) value_layout = QFormLayout() # add each series for v in self.series_table.values(): v.addSeries(_x2idx, _idx2x, chart, self.axis_x, self.axis_y) if v.show_value: value_layout.addWidget(v.show_group) # create chartview and layout for view and value chartview = ChartView(chart, self.wizard) chartview.setRenderHint(QPainter.Antialiasing) global_layout = QHBoxLayout() global_layout.addWidget(chartview, self.chart_stretch) global_layout.addLayout(value_layout) return global_layout def updateValue(self, _x): for v in self.series_table.values(): if v.show_value: v.updateValue(_x)
class PlotterPane(QChartView): """ This plotter widget makes viewing sensor data easy! This widget represents a chart that will look for tuple data from the MicroPython REPL, Python 3 REPL or Python 3 code runner and will auto-generate a graph. """ data_flood = pyqtSignal() def __init__(self, parent=None): super().__init__(parent) # Holds the raw input to be checked for actionable data to display. self.input_buffer = [] # Holds the raw actionable data detected while plotting. self.raw_data = [] self.setObjectName('plotterpane') self.max_x = 100 # Maximum value along x axis self.max_y = 1000 # Maximum value +/- along y axis self.flooded = False # Flag to indicate if data flooding is happening. # Holds deques for each slot of incoming data (assumes 1 to start with) self.data = [deque([0] * self.max_x), ] # Holds line series for each slot of incoming data (assumes 1 to start # with). self.series = [QLineSeries(), ] # Ranges used for the Y axis (up to 1000, after which we just double # the range). self.y_ranges = [1, 5, 10, 25, 50, 100, 250, 500, 1000] # Set up the chart with sensible defaults. self.chart = QChart() self.chart.legend().hide() self.chart.addSeries(self.series[0]) self.axis_x = QValueAxis() self.axis_y = QValueAxis() self.axis_x.setRange(0, self.max_x) self.axis_y.setRange(-self.max_y, self.max_y) self.axis_x.setLabelFormat("time") self.axis_y.setLabelFormat("%d") self.chart.setAxisX(self.axis_x, self.series[0]) self.chart.setAxisY(self.axis_y, self.series[0]) self.setChart(self.chart) self.setRenderHint(QPainter.Antialiasing) def process_bytes(self, data): """ Takes raw bytes and, if a valid tuple is detected, adds the data to the plotter. The the length of the bytes data > 1024 then a data_flood signal is emitted to ensure Mu can take action to remain responsive. """ # Data flooding guards. if self.flooded: return if len(data) > 1024: self.flooded = True self.data_flood.emit() return data = data.replace(b'\r\n', b'\n') self.input_buffer.append(data) # Check if the data contains a Python tuple, containing numbers, on a # single line (i.e. ends with \n). input_bytes = b''.join(self.input_buffer) lines = input_bytes.split(b'\n') for line in lines: if line.startswith(b'(') and line.endswith(b')'): # Candidate tuple. Extract the raw bytes into a numeric tuple. raw_values = [val.strip() for val in line[1:-1].split(b',')] numeric_values = [] for raw in raw_values: try: numeric_values.append(int(raw)) # It worked, so move onto the next value. continue except ValueError: # Try again as a float. pass try: numeric_values.append(float(raw)) except ValueError: # Not an int or float, so ignore this value. continue if numeric_values: # There were numeric values in the tuple, so use them! self.add_data(tuple(numeric_values)) # Reset the input buffer. self.input_buffer = [] if lines[-1]: # Append any bytes that are not yet at the end of a line, for # processing next time we read data from self.serial. self.input_buffer.append(lines[-1]) def add_data(self, values): """ Given a tuple of values, ensures there are the required number of line series, add the data to the line series, update the range of the chart so the chart displays nicely. """ # Store incoming data to dump as CSV at the end of the session. self.raw_data.append(values) # Check the number of incoming values. if len(values) != len(self.series): # Adjust the number of line series. value_len = len(values) series_len = len(self.series) if value_len > series_len: # Add new line series. for i in range(value_len - series_len): new_series = QLineSeries() self.chart.addSeries(new_series) self.chart.setAxisX(self.axis_x, new_series) self.chart.setAxisY(self.axis_y, new_series) self.series.append(new_series) self.data.append(deque([0] * self.max_x)) else: # Remove old line series. for old_series in self.series[value_len:]: self.chart.removeSeries(old_series) self.series = self.series[:value_len] self.data = self.data[:value_len] # Add the incoming values to the data to be displayed, and compute # max range. max_ranges = [] for i, value in enumerate(values): self.data[i].appendleft(value) max_ranges.append(max([max(self.data[i]), abs(min(self.data[i]))])) if len(self.data[i]) > self.max_x: self.data[i].pop() # Re-scale y-axis. max_y_range = max(max_ranges) y_range = bisect.bisect_left(self.y_ranges, max_y_range) if y_range < len(self.y_ranges): self.max_y = self.y_ranges[y_range] elif max_y_range > self.max_y: self.max_y += self.max_y elif max_y_range < self.max_y / 2: self.max_y = self.max_y / 2 self.axis_y.setRange(-self.max_y, self.max_y) # Ensure floats are used to label y axis if the range is small. if self.max_y <= 5: self.axis_y.setLabelFormat("%2.2f") else: self.axis_y.setLabelFormat("%d") # Update the line series with the data. for i, line_series in enumerate(self.series): line_series.clear() xy_vals = [] for j in range(self.max_x): val = self.data[i][self.max_x - 1 - j] xy_vals.append((j, val)) for point in xy_vals: line_series.append(*point) def set_theme(self, theme): """ Sets the theme / look for the plotter pane. """ if theme == 'day': self.chart.setTheme(QChart.ChartThemeLight) elif theme == 'night': self.chart.setTheme(QChart.ChartThemeDark) else: self.chart.setTheme(QChart.ChartThemeHighContrast)