def __init__(self): super().__init__() series = QLineSeries() series.setPointsVisible(True) series.setPointLabelsVisible(True) series.setPointLabelsFormat("(@xPoint, @yPoint)") series.append(0, 6) series.append(2, 4) series.append(3, 8) series.append(7, 4) series.append(10, 5) chart = QChart() chart.setTitle("Line Chart Example") chart.setAnimationOptions(QChart.SeriesAnimations) chart.legend().hide() chart.addSeries(series) chart.createDefaultAxes() chart_view = QChartView() chart_view.setChart(chart) chart_view.setRenderHint(QPainter.Antialiasing) self.setCentralWidget(chart_view)
def create_linechart(self): series = QLineSeries(self) series.append(0, 6) series.append(2, 4) series.append(3, 8) series.append(7, 4) series.append(10, 5) series << QPointF(11, 1) << QPointF(13, 3) << QPointF( 17, 6) << QPointF(18, 3) << QPointF(20, 2) chart = QChart() chart.addSeries(series) chart.createDefaultAxes() chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle("Line Chart Example") chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartview = QChartView(chart) chartview.setRenderHint(QPainter.Antialiasing) self.setCentralWidget(chartview)
class TestWindow(QMainWindow): def __init__(self, parent=None): super(TestWindow, self).__init__(parent=parent) self.ncurves = 0 self.timer = QTimer(self) self.chart = QChart() self.chart.legend().hide() self.view = QChartView(self.chart) self.view.setRenderHint(QPainter.Antialiasing) self.setCentralWidget(self.view) self.count = 0. #self.timer.timeout.connect(functools.partial(self.update, a=1)) #self.timer.start(100) #def update(self, a): #print(self.chart.series) def set_title(self, title): self.chart.setTitle(title) def add_data(self, xdata, ydata, color=None): curve = QLineSeries() pen = curve.pen() if color is not None: pen.setColor(color) pen.setWidthF(.6) curve.setPen(pen) curve.setUseOpenGL(True) curve.append(series_to_polyline(xdata, ydata)) self.chart.addSeries(curve) self.chart.createDefaultAxes() self.ncurves += 1
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 update_particles(particles): animation_chart = QChart() reals = QScatterSeries() pen_reals = reals.pen() pen_reals.setBrush(QtGui.QColor("white")) reals.setMarkerSize(5) reals.setColor(QtGui.QColor("red")) reals.setPen(pen_reals) for particle in particles: reals.append(particle, 0) animation_chart.addSeries(reals) animation_chart.setBackgroundBrush(QtGui.QColor(41, 43, 47)) animation_chart.createDefaultAxes() animation_chart.legend().hide() animation_chart.setContentsMargins(-10, -10, -10, -10) animation_chart.layout().setContentsMargins(0, 0, 0, 0) animation_chart.axisX().setTickCount(17) animation_chart.axisY().setTickCount(3) animation_chart.axisX().setLabelsColor(QtGui.QColor("white")) animation_chart.axisX().setGridLineColor(QtGui.QColor("grey")) animation_chart.axisX().setRange(-4, 12) animation_chart.axisY().setRange(-1, 1) animation_chart.axisY().setLabelsColor(QtGui.QColor("white")) animation_chart.axisY().setGridLineColor(QtGui.QColor("grey")) form.widget_animation.setChart(animation_chart)
def __init__(self): super().__init__() # window size self.setMinimumSize(600, 400) # data raw_data = [ (0, 6), (2, 4), (3, 8), (7, 4), (10, 5), (11, 1), (13, 3), (17, 6), (18, 3), (20, 2) ] series = QLineSeries() for d in raw_data: series.append(*d) # chart object chart = QChart() chart.legend().hide() chart.addSeries(series) # data feeding chart.createDefaultAxes() # displaying chart chart_view = QChartView(chart) chart_view.setRenderHint(QPainter.Antialiasing) self.setCentralWidget(chart_view)
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 __init__(self, *args, **kwargs): super(Window, self).__init__(*args, **kwargs) self.resize(400, 300) # 抗锯齿 self.setRenderHint(QPainter.Antialiasing) # 图表 chart = QChart() self.setChart(chart) # 设置标题 chart.setTitle('Simple barchart example') # 开启动画效果 chart.setAnimationOptions(QChart.SeriesAnimations) # 添加Series series = self.getSeries() chart.addSeries(series) # 分类 categories = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] # 分类x轴 axis = QBarCategoryAxis() axis.append(categories) # 创建默认轴线 chart.createDefaultAxes() # 替换默认x轴 chart.setAxisX(axis, series) # 显示图例 chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom)
class MainWindow(ChartViewToolTips): def __init__(self): super().__init__() series = QLineSeries() series.setPointsVisible(True) series.setPointLabelsVisible(True) series.setPointLabelsFormat("(@xPoint, @yPoint)") series.hovered.connect(self.show_series_tooltip) series.append(0, 6) series.append(2, 4) series.append(3, 8) series.append(7, 4) series.append(10, 5) self._chart = QChart() self._chart.setMinimumSize(640, 480) self._chart.setTitle("Line Chart Example") self._chart.setAnimationOptions(QChart.SeriesAnimations) self._chart.legend().hide() self._chart.addSeries(series) self._chart.createDefaultAxes() self.setChart(self._chart)
def make_bar_chart(self): chart = QChart() chart.setTitle("현재 재고 현황") chart.setAnimationOptions(QChart.SeriesAnimations) item_statistics_dict = self.statistics_manager.get_item_statistics_dict( ) categories = ["2020년"] series = QBarSeries() for key, value in item_statistics_dict.items(): set = QBarSet(key) set << value[REMAIN_COUNT] series.append(set) chart.addSeries(series) axis = QBarCategoryAxis() axis.append(categories) chart.createDefaultAxes() chart.setAxisX(axis, series) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) self.barChartView = QChartView(chart) self.barChartView.setRenderHint(QPainter.Antialiasing) self.statisticsWidget.setWidget(self.barChartView)
def setupChart(self): """Set up the GUI's series and chart.""" # Collect x and y data values from the CSV file x_values, y_values = self.loadCSVFile() # Get the largest x and y values; Used for setting the chart's axes x_max, y_max = max(x_values), max(y_values) # Create numpy arrays from the x and y values x_values = np.array(x_values) y_values = np.array(y_values) # Calculate the regression line coefficients = linearRegression(x_values, y_values) # Create chart object chart = QChart() chart.setTitle("Auto Insurance for Geographical Zones in Sweden") chart.legend().hide() # Create scatter series and add points to the series scatter_series = QScatterSeries() scatter_series.setName("DataPoints") scatter_series.setMarkerSize(9.0) scatter_series.hovered.connect(self.displayPointInfo) for value in range(0, self.row_count - 1): scatter_series.append(x_values[value], y_values[value]) scatter_series.setBorderColor(QColor('#000000')) # Create line series and add points to the series line_series = QLineSeries() line_series.setName("RegressionLine") # Calculate the regression line for x in x_values: y_pred = coefficients[0] + coefficients[1] * x line_series.append(x, y_pred) # Add both series to the chart and create x and y axes chart.addSeries(scatter_series) chart.addSeries(line_series) chart.createDefaultAxes() axis_x = chart.axes(Qt.Horizontal) axis_x[0].setTitleText("Number of Claims") axis_x[0].setRange(0, x_max) axis_x[0].setLabelFormat("%i") axis_y = chart.axes(Qt.Vertical) axis_y[0].setTitleText( "Total Payment in Swedish Kronor (in thousands)") axis_y[0].setRange(0, y_max + 20) # Create QChartView object for displaying the chart chart_view = QChartView(chart) v_box = QVBoxLayout() v_box.addWidget(chart_view) self.setLayout(v_box)
class Chart(QWidget): def __init__(self, chartKey, data, frame, parent=None): super(Chart, self).__init__(parent) self.frame = frame self.data = data self.create_chart(chartKey) def create_chart(self, chartKey): self.series = QPieSeries() self.series.setHoleSize(0.35) self.chart = QChart() #Add series to the chart self.addSeries(chartKey) # for the background and title self.chart.setAnimationOptions(QChart.SeriesAnimations) self.chart.setTitle("Code Size Visualizer") self.chart.legend().setVisible(True) self.chart.legend().setAlignment(Qt.AlignRight) self.chart.setTheme(QChart.ChartThemeBlueCerulean) self.chartview = QChartView(self.chart) self.chartview.setRenderHint(QPainter.Antialiasing) #each section of the pie chart def addSeries(self, key): self.chart.removeAllSeries() self.series = QPieSeries() self.series.setHoleSize(0.35) #Show chartview only if the content length is less than 6. Otherwise show a table view if len(self.data[key]) < 6: #print('length',self.data, key) for key, value in self.data[key].items(): print('key, value', key, value) slice_ = QPieSlice(str(key), value) self.series.append(slice_) self.series.setLabelsVisible() self.series.setLabelsPosition(QPieSlice.LabelInsideHorizontal) for slice in self.series.slices(): #slice.setLabel(slice.label()) slice.setLabel(slice.label() + ' - ' + str(slice.value()) + ' B ') self.chart.addSeries(self.series) self.frame.frame.hide() self.chart.show() else: self.table = TableView(self.data[key], len(self.data[key]), 1) if self.frame.ly.count() > 0: self.frame.ly.itemAt(0).widget().setParent(None) self.frame.ly.addWidget(self.table) self.frame.frame.show() self.chart.hide()
def drawD2(self): if self.vtkViewer.reader == None: return num = self.inputD2.text() try: num = list(map(int, num.split(' '))) except Exception: return if len(num) != 2 or num[0] <= 1 or num[1] <= 1: return self.clear() histogram, scale = self.vtkViewer.d2Sample(num[0], num[1]) d2Chart = QChart() d2Chart.legend().hide() polyline = QPolygonF(num[0]) pointer = polyline.data() dtype, tinfo = np.float, np.finfo pointer.setsize(2*polyline.size()*tinfo(dtype).dtype.itemsize) memory = np.frombuffer(pointer, dtype) memory[:(num[0]-1)*2+1:2] = scale memory[1:(num[0]-1)*2+2:2] = histogram curve = QLineSeries() curve.append(polyline) d2Chart.addSeries(curve) d2Chart.createDefaultAxes() ChartView = QChartView(d2Chart) self.d2ChartLayout.addWidget(ChartView)
def __init__(self): super(MainWindow, self).__init__() ''' Load the UI file from disk (UI file was created in QT Designer) ''' uic.loadUi("mainwindow.ui", self) ''' Create an instance of the database class ''' self.dbase = db.database( ) # Create an instance of the database as self.dbase '''call the Connect method on our new database object (Creates a database connection) ''' self.dbase.Connect() self.conn = self.dbase.getConn() ''' Set up the menubar ''' self.createMenus() self.carsModel = cars.carsModel() setupUI.doSetup(self) self.dbase.populateView(self, "select * from car order by make asc", self.carsModel) mySeries = QPieSeries() mySeries.append("jane", 2) mySeries.append("joe", 8) chart = QChart() chart.addSeries(mySeries) chart.setTitle("Simple piechart example") chart.legend().hide()
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)
class ChartWidget: def __init__(self): self.model = QChart() self.view = QChartView() self.view.setChart(self.model) self.model.legend().setAlignment(Qt.AlignBottom) self.view.setRenderHint(QPainter.Antialiasing) def show(self): self.view.show() def exit(self): self.view.close() @property def title(self): return self.model.title() @title.setter def title(self, title): self.model.setTitle(title) def add_series(self, x_list, y_list, name): series = QLineSeries() series.setName(name) for x, y in zip(x_list, y_list): series.append(x, y) self.model.addSeries(series) self.model.createDefaultAxes()
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)
class TestWindow(QMainWindow): def __init__(self, parent=None): super(TestWindow, self).__init__(parent=parent) self.ncurves = 0 self.chart = QChart() self.chart.legend().hide() self.view = QChartView(self.chart) self.view.setRenderHint(QPainter.Antialiasing) self.setCentralWidget(self.view) def set_title(self, title): self.chart.setTitle(title) def add_data(self, xdata, ydata, color=None): curve = QLineSeries() #pen = curve.pen() #if color is not None: # pen.setColor(color) #pen.setWidthF(1) #curve.setPen(pen) curve.setUseOpenGL(True) curve.append(series_to_polyline(xdata, ydata)) self.chart.addSeries(curve) self.chart.createDefaultAxes() self.ncurves += 1
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 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 __init__(self, series: QLineSeries, title: str, xTitle: str, yTitle: str, minimumSize=QSize(400, 400), *args): super().__init__(*args) chart = QChart() chart.setTitle(title) axisX = QValueAxis(chart) axisX.setTitleText(xTitle) chart.setAxisX(axisX) axisY = QValueAxis(chart) axisY.setTitleText(yTitle) chart.setAxisY(axisY) chart.legend().show() chart.legend().setAlignment(Qt.AlignBottom) self.setChart(chart) self.set_series(series) self.setMinimumSize(minimumSize) self.setRenderHint(QPainter.Antialiasing) self.pan = Pan(self)
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 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 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)
class ErrorLineChart(QFrame): def __init__(self, nseries=1, series_names=None): super().__init__() if nseries < 1: raise ValueError( 'The number of serieses must be larger than zero.') self.nseries = nseries self.series_names = series_names layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.setMinimumHeight(110) self.setMinimumWidth(400) self.serieses = [QLineSeries() for _ in range(self.nseries)] self.chart = QChart() if self.series_names is None: self.chart.legend().hide() for idx, series in enumerate(self.serieses): self.chart.addSeries(series) if self.series_names is not None: series.setName(self.series_names[idx]) self.chart.createDefaultAxes() self.chart.layout().setContentsMargins(0, 0, 0, 0) # self.chart.setTheme(QChart.ChartThemeDark) self.chart.axisY().setTickCount(3) chart_view = QChartView(self.chart) chart_view.setRenderHint(QPainter.Antialiasing) layout.addWidget(chart_view) self.x_max = 2 self.y_pts = list() def append_point(self, x, y, series_idx=0): self.serieses[series_idx].append(x, y) self.x_max = max(x, self.x_max) self.y_pts.append(y) if self.x_max > 100: self.chart.axisX().setRange(self.x_max - 100, self.x_max) y_max = max(self.y_pts[-100:]) self.serieses[series_idx].remove(self.x_max - 100, self.y_pts[self.x_max - 101]) else: self.chart.axisX().setRange(1, self.x_max) y_max = max(self.y_pts) self.chart.axisY().setRange(0, y_max + y_max / 5) def clear(self): self.chart.removeAllSeries() self.serieses = [QLineSeries() for _ in range(self.nseries)] for idx, series in enumerate(self.serieses): self.chart.addSeries(series) if self.series_names is not None: series.setName(self.series_names[idx]) self.chart.createDefaultAxes() self.chart.axisY().setTickCount(3) self.x_max = 2 self.y_pts = list()
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 build(self): self.setWindowTitle('Emoreco') self.setWindowIcon(QIcon(root + 'Logo.ico')) oImage = QImage(root + "Background.png") palette = QPalette() palette.setBrush(QPalette.Window, QBrush(oImage)) self.setPalette(palette) oImage = QPixmap(root + "Ok.png") palette = QPalette() palette.setBrush(self.OkButton.backgroundRole(), QBrush(oImage)) self.OkButton.setFlat(1) self.OkButton.setAutoFillBackground(1) self.OkButton.setPalette(palette) self.OkButton.clicked.connect(self.closeWindow) set_list = [ QBarSet('Circulatory'), QBarSet('Digestive'), QBarSet('Endocrine'), QBarSet('Integumentary'), QBarSet('Lymphatic'), QBarSet('Muscular'), QBarSet('Nervous'), QBarSet('Excretory'), QBarSet('Reproductive'), QBarSet('Respiratory'), QBarSet('Skeletal') ] categories = [''] series = QBarSeries() chart = QChart() axis = QBarCategoryAxis() for i in range(sys_n): set_list[i].append([dis_prediction[i]]) series.append(set_list[i]) chart.addSeries(series) axis.append(categories) chart.setTitle('Our prediction (%)') chart.createDefaultAxes() chart.setAxisX(axis, series) chart.legend().setAlignment(Qt.AlignLeft) chart.setBackgroundBrush(QColor(61, 56, 63, 0)) chartView = QChartView(chart) chartView.chart().setAnimationOptions(QChart.AllAnimations) base = self.gridLayout base.addWidget(chartView) self.show()
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)
class ChartWidget(QWidget): def __init__(self, parent=None, ticker="BTCUSDT"): super().__init__(parent) uic.loadUi("resource/chart.ui", self) self.ticker = ticker self.viewLimit = 10 self.tm = [] self.priceData = QCandlestickSeries() self.priceData.setDecreasingColor(Qt.red) self.priceData.setIncreasingColor(Qt.green) 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, o, h, l, c): if len(self.tm) == self.viewLimit: self.priceData.remove(0) self.tm.remove(0) dt = QDateTime.currentDateTime() self.priceData.append(QCandlestickSet(o, h, l, c)) print(dt.toMSecsSinceEpoch()) print(type(dt.toMSecsSinceEpoch())) self.tm.append(dt.toMSecsSinceEpoch()) self.__updateAxis() def __updateAxis(self): pvs = self.tm dtStart = QDateTime.fromMSecsSinceEpoch(int(pvs[0])) if len(self.priceData) == self.viewLimit: dtLast = QDateTime.fromMSecsSinceEpoch(int(pvs[-1])) else: dtLast = dtStart.addSecs(self.viewLimit) ax = self.priceChart.axisX() ax.setRange(dtStart, dtLast)
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
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)