def bubbleSorting(self, array): # Sorting Algorithm for Bubble Sort n = len(array) self.progressBar.setMaximum(n - 2) x = [] for lel in range(1, n + 1): x.append(lel) for i in range(n): # Traverse through all array elements # Last i elements are already in place for j in range(0, n - i - 1): # Traverse the array from 0 to n-i-1 if self.checkBoxStop.isChecked(): while self.checkBoxStop.isChecked() == 1: QtTest.QTest.qWait(50) else: speed = (4000 - (self.horizontalSliderSpeed.value()) * 1000) / 2 QApplication.processEvents() QtTest.QTest.qWait(speed) self.graphicsViewVisualize.clear() bg1 = pyqtgraph.BarGraphItem(x=x, height=array, width=0.3, brush='r') self.graphicsViewVisualize.addItem(bg1) if int(array[j]) > int( array[j + 1]): # Swap if the element found is greater array[j], array[j + 1] = int(array[j + 1]), int( array[j]) # than the next element self.graphicsViewVisualize.clear() bg1 = pyqtgraph.BarGraphItem(x=x, height=array, width=0.3, brush='r') self.graphicsViewVisualize.addItem(bg1) self.progressBar.setValue(i) return array
def PlotVolumeChart(self, plt, uniqueID): p3 = pg.ViewBox() p3.setObjectName(uniqueID) ax3 = pg.AxisItem('right') plt.layout.addItem(ax3, 2,3) plt.scene().addItem(p3) ax3.linkToView(p3) p3.setXLink(plt) ax3.setZValue(-100000) if uniqueID.find('CE') != -1 or uniqueID.find('PE') != -1: ax3.setLabel('Volume', color='blue') else: ax3.setLabel('Volume', color='yellow') item2 = None if uniqueID.find('CE') != -1: item2 = pg.BarGraphItem(x=range(2), height=[0,0], width=0.9, name='Volume', brush='b', pen='b') elif uniqueID.find('PE') != -1: item2 = pg.BarGraphItem(x=range(2), height=[0,0], width=0.3, name='Volume', brush='r', pen='r') else: item2 = pg.BarGraphItem(x=range(2), height=[0,0], width=0.5, name='Volume', brush='g', pen='y') item2.setOpacity(0.5) item2.setObjectName(uniqueID) p3.addItem(item2) self.plotsDict[p3] = plt self.graphs.append(item2) plt.vb.sigResized.connect(self.updateViews)
def on_pushButton_2_clicked(self): """ Slot documentation goes here. """ '''如果没有进行第一次绘图,就开始绘图,然后做绘图标记,否则就什么都不做''' try: self.first_plot_flag # 检测是否进行过第一次绘图。 except: plt = self.pyqtgraph2.addPlot(title='绘制条状图') x = np.arange(10) y1 = np.sin(x) y2 = 1.1 * np.sin(x + 1) y3 = 1.2 * np.sin(x + 2) bg1 = pg.BarGraphItem(x=x, height=y1, width=0.3, brush='r') bg2 = pg.BarGraphItem(x=x + 0.33, height=y2, width=0.3, brush='g') bg3 = pg.BarGraphItem(x=x + 0.66, height=y3, width=0.3, brush='b') plt.addItem(bg1) plt.addItem(bg2) plt.addItem(bg3) self.pyqtgraph2.nextRow() p4 = self.pyqtgraph2.addPlot(title="参数图+显示网格") x = np.cos(np.linspace(0, 2 * np.pi, 1000)) y = np.sin(np.linspace(0, 4 * np.pi, 1000)) p4.plot(x, y, pen=pg.mkPen(color='d', width=2)) p4.showGrid(x=True, y=True) # 显示网格 self.first_plot_flag = True # 第一次绘图后进行标记
def heapSort(self, arr): """ :param arr: Array :return: Sorted Array """ lengthArray = len(arr) x = [] self.progressBar.setMaximum(lengthArray - 2) for lel in range(1, lengthArray + 1): x.append(lel) # Build a maxheap. for i in range(lengthArray, -1, -1): self.heapify(arr, lengthArray, i) # One by one extract elements for i in range(lengthArray - 1, 0, -1): if self.checkBoxStop.isChecked(): while self.checkBoxStop.isChecked() == 1: QtTest.QTest.qWait(50) else: speed = (4000 - (self.horizontalSliderSpeed.value()) * 1000) / 2 QApplication.processEvents() QtTest.QTest.qWait(speed) self.graphicsViewVisualize.clear() bg1 = pyqtgraph.BarGraphItem(x=x, height=arr, width=0.3, brush='r') self.graphicsViewVisualize.addItem(bg1) arr[i], arr[0] = arr[0], arr[i] # swap self.graphicsViewVisualize.clear() bg1 = pyqtgraph.BarGraphItem(x=x, height=arr, width=0.3, brush='r') self.graphicsViewVisualize.addItem(bg1) self.progressBar.setValue(lengthArray - i) self.heapify(arr, i, 0)
def draw_indexer(self): i = 0 for indexer_name, values in self.indexer_value_dic.items(): if indexer_name == 'HIST': n = 0 up_num = [] up_value = [] down_num = [] down_value = [] for v in values: if v >= 0: up_value.append(v) up_num.append(n) else: down_value.append(v) down_num.append(n) n += 1 self.hist_item_up = pg.BarGraphItem(x=up_num, height=up_value, width=0.3, brush='r') self.hist_item_down = pg.BarGraphItem(x=down_num, height=down_value, width=0.3, brush='g') self.plt.addItem(self.hist_item_up) self.plt.addItem(self.hist_item_down) else: c = self.indexer_color_dic[indexer_name][0] self.plt_dic[indexer_name] = self.plt.plot(name=indexer_name, pen=c) self.plt_dic[indexer_name].setData(values) i += 1
def example1(): """ Simple example using BarGraphItem """ import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import numpy as np win = pg.plot() win.setWindowTitle('pyqtgraph example: BarGraphItem') x = np.arange(10) y1 = np.sin(x) y2 = 1.1 * np.sin(x + 1) y3 = 1.2 * np.sin(x + 2) bg1 = pg.BarGraphItem(x=x, height=y1, width=0.3, brush='r') bg2 = pg.BarGraphItem(x=x + 0.33, height=y2, width=0.3, brush='g') bg3 = pg.BarGraphItem(x=x + 0.66, height=y3, width=0.3, brush='b') win.addItem(bg1) win.addItem(bg2) win.addItem(bg3) # Final example shows how to handle mouse clicks: class BarGraph(pg.BarGraphItem): def mouseClickEvent(self, event): print("clicked") bg = BarGraph(x=x, y=y1 * 0.3 + 2, height=0.4 + y1 * 0.2, width=0.8) win.addItem(bg) import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
def radixSort(self, arr): # Find the maximum number to know number of digits max1 = max(arr) ArrayLength = len(arr) x = [] self.progressBar.setMaximum(100) for lel in range(1, ArrayLength + 1): x.append(lel) # Do counting sort for every digit. Note that instead # of passing digit number, exp is passed. exp is 10^i # where i is current digit number exp = 1 while max1 / exp > 1: if self.checkBoxStop.isChecked(): while self.checkBoxStop.isChecked() == 1: QtTest.QTest.qWait(50) else: speed = (4000 - (self.horizontalSliderSpeed.value()) * 1000) / 2 QApplication.processEvents() QtTest.QTest.qWait(speed) self.graphicsViewVisualize.clear() bg1 = pyqtgraph.BarGraphItem(x=x, height=arr, width=0.3, brush='r') self.graphicsViewVisualize.addItem(bg1) self.countingSortRadix(arr, exp) exp *= 10 self.graphicsViewVisualize.clear() QApplication.processEvents() bg1 = pyqtgraph.BarGraphItem(x=x, height=arr, width=0.3, brush='r') self.graphicsViewVisualize.addItem(bg1) self.progressBar.setValue(exp)
def displayBarMultiVar(self): self.setNormalLayout() self.clearPlot() x_left = list(map(lambda x: x - .25, self.x_axis_monthly)) x_right = list(map(lambda x: x + .25, self.x_axis_monthly)) self.legend = self.currentPlot.addLegend() incomes_bar = pg.BarGraphItem(x=x_left, height=self.incomes, width=0.25, brush='g', name='Incomes') expenditures_bar = pg.BarGraphItem(x=self.x_axis_monthly, height=self.expenditures, width=0.25, brush='r', name='Expenditures') savings_bar = pg.BarGraphItem(x=x_right, height=self.savings, width=0.25, brush='b', name='Savings') self.currentPlot.addItem(incomes_bar) self.currentPlot.addItem(expenditures_bar) self.currentPlot.addItem(savings_bar) #color of BarGraphItem currently not displaying with legend. Note that addItem is also NOT using the name keyword defined within incomes_bar, etc. self.legend.addItem(incomes_bar, name="Green: Incomes") self.legend.addItem(expenditures_bar, name="Red: Expenditures") self.legend.addItem(savings_bar, name="Blue: Savings") self.currentPlot.setTitle( "Comparison of Monthly Income, Expenditures, and Savings") self.xAxis.setTicks([self.month_x_ticks])
def plotbar(arrY, x=None, color=None, hold=None, figureNo=None, width=0.6): global CURR, PLOTS arrY = N.asarray( arrY ) if x is not None: x = N.asarray(x) else: x = N.arange(arrY.shape[-1]) if len(arrY.shape) > 1 and arrY.shape[0] > arrY.shape[1]: arrY = N.transpose(arrY) pw = plothold(hold, figureNo) append = pw == pg if append: pw = pg.plot() kwd = {} kwd['pen'] = _pen(pw, color) kwd['brush'] = _brush(pw, color) kwd['width'] = width if len(arrY.shape) == 1: bg = pg.BarGraphItem(x=x, height=arrY, **kwd) pw.addItem(bg) else: data = [] for i in range(arr.shape[0]): bg = pg.BarGraphItem(x=x, height=arrY[i], **kwd) pw.addItem(bg) if append: PLOTS.append(pw)
def on_pushButton_2_clicked(self): ''' Slot documentation goes here. ''' '''如果沒有進行第一次繪圖,就開始繪圖,然後做繪圖標記,否則就什麼都不做''' try: self.first_plot_flag # 檢測是否進行過第一次繪圖。 except: plt = self.pyqtgraph2.addPlot(title='繪製長條圖') x = np.arange(10) y1 = np.sin(x) y2 = 1.1 * np.sin(x + 1) y3 = 1.2 * np.sin(x + 2) bg1 = pg.BarGraphItem(x=x, height=y1, width=0.3, brush='r') bg2 = pg.BarGraphItem(x=x + 0.33, height=y2, width=0.3, brush='g') bg3 = pg.BarGraphItem(x=x + 0.66, height=y3, width=0.3, brush='b') plt.addItem(bg1) plt.addItem(bg2) plt.addItem(bg3) self.pyqtgraph2.nextRow() p4 = self.pyqtgraph2.addPlot(title="參數圖+顯示格子") x = np.cos(np.linspace(0, 2 * np.pi, 1000)) y = np.sin(np.linspace(0, 4 * np.pi, 1000)) p4.plot(x, y, pen=pg.mkPen(color='d', width=2)) p4.showGrid(x=True, y=True) # 顯示格子 self.first_plot_flag = True # 第一次繪圖後進行標記
def __init__(self, chan_max, rebin, roi_rebin, **kwargs): super().__init__(**kwargs) self.contextMenu = [] # create initial histogram self.hist = pg.BarGraphItem(x0=np.arange(chan_max), height=rebin,\ width=1, pen=self.hist_color, brush=self.hist_color) self.addItem(self.hist) # create ROI histogram self.roi = pg.BarGraphItem(x0=np.arange(chan_max), height=roi_rebin,\ width=1, pen=self.roi_color, brush=self.roi_color) self.addItem(self.roi) # create roi fit scatterplot self.fit = MCBScatter(pen='k') self.addItem(self.fit) # create initial marker line self.line = pg.InfiniteLine(pos=0, pen='k', movable=True) self.addItem(self.line) # create initial ROI box self.box = MCBROI(pen='k', movable=False) self.addItem(self.box) # hide ROI box when marker line is dragged self.line.sigDragged.connect(self.box.hide)
def init_ui(self): """""" pg.setConfigOptions(antialias=True) self.pnl_plot = self.addPlot(title="每日盈亏", axisItems={ "bottom": DateAxis(self.dates, orientation="bottom", maxTickLength=-10) }) zero_color = 'w' profit_color = 'r' loss_color = 'g' self.zero_pnl_bar = pg.BarGraphItem(x=[], height=[], width=0.3, brush=zero_color, pen=zero_color) self.profit_pnl_bar = pg.BarGraphItem(x=[], height=[], width=0.3, brush=profit_color, pen=profit_color) self.loss_pnl_bar = pg.BarGraphItem(x=[], height=[], width=0.3, brush=loss_color, pen=loss_color) self.pnl_plot.addItem(self.zero_pnl_bar) self.pnl_plot.addItem(self.profit_pnl_bar) self.pnl_plot.addItem(self.loss_pnl_bar)
def plot_spectrum(plot_widget, spectrum, name, left_label, bottom_label, color, limit=None): plot_widget.setTitle(name + ' spectrum') plot_widget.setLabel('left', left_label, size='30') plot_widget.setLabel('bottom', bottom_label, size='30') plot_widget.setBackground('w') plot_widget.showGrid(x=True, y=True) # pen = pg.mkPen(brush=color) # pg.BarGraphItem(x=spectrum.fs, height=spectrum.amps, width=0.6, ) limit = util.find_nearest_idx(spectrum, limit, 1) if limit is None: bar_graph = pg.BarGraphItem(x=spectrum.fs, width=2.5, height=spectrum.amps, brush=color) plot_widget.addItem(bar_graph) else: bar_graph = pg.BarGraphItem(x=spectrum.fs[:limit], width=2.5, height=spectrum.amps[:limit], brush=color) plot_widget.addItem(bar_graph) plot_widget.getPlotItem().getViewBox().enableAutoRange('y', 0.95)
def re_draw_indexer(self): for pname, values in self.indexer_value_dic.items(): if pname == 'HIST': self.plt.removeItem(self.hist_item_up) self.plt.removeItem(self.hist_item_down) n = 0 up_num = [] up_value = [] down_num = [] down_value = [] for v in values: if v >= 0: up_value.append(v) up_num.append(n) else: down_value.append(v) down_num.append(n) n += 1 self.hist_item_up = pg.BarGraphItem(x=up_num, height=up_value, width=0.3, brush='r') self.hist_item_down = pg.BarGraphItem(x=down_num, height=down_value, width=0.3, brush='g') self.plt.addItem(self.hist_item_up) self.plt.addItem(self.hist_item_down) else: self.plt_dic[pname].setData(values)
def CoincView(self): if self.curTab == 0: chGood = np.array([1, 2, 4, 5, 7, 8]) chErr = np.array([0, 3, 6]) count = self.coincidences[0:3, 3:6].flatten() pltFig = self.pltCoinc elif self.curTab == 1: chGood = np.array([0, 3]) chErr = np.array([1, 2]) count = self.coincidences[0:2, 2:4].flatten() pltFig = self.pltCoincVis xdict = dict(enumerate(count)) bgGood = pg.BarGraphItem(x=chGood, height=count[chGood], width=0.7, brush='b') bgErr = pg.BarGraphItem(x=chErr, height=count[chErr], width=0.7, brush='r') ax = pltFig.getAxis('bottom') pltFig.clear() ax.setTicks([xdict.items(), []]) pltFig.addItem(bgGood) pltFig.addItem(bgErr)
def makeGraph(graphView): global displayingfile global counter global best_source_file with open(best_source_file, "w") as t: # Initialize file to store best source later pass counter = 0 pg.setConfigOptions(antialias=True) prev = 2 # Gap after making bar graph of 1 newspaper for file in displayingfile: counter += 1 y_axis_pos = [] y_axis_neg = [] y_axis_zero = [] with open(file, "r") as f: for line in f: if line.startswith(">>"): num = float(line[3:].rstrip("\n")) if num > 0: y_axis_pos.append(num) if num < 0: y_axis_neg.append(num) if num == 0: y_axis_zero.append(1) pos_x = [prev] # Green bar neg_x = [prev + 0.5] # Red bar after a gap of 0.5 in x axis neu_x = [prev + 1 ] # White bar after a gap of 1 in x axis from Green bar pos_y = [sum(y_axis_pos)] neg_y = [abs(sum(y_axis_neg)) ] # To display in it positive y-axis, take absolute value neu_y = [sum(y_axis_zero)] writeData(sum(y_axis_pos), abs(sum(y_axis_neg)), sum(y_axis_zero)) pos = pg.BarGraphItem(x=np.array(pos_x), height=np.array(pos_y), width=0.5, brush=(0, 198, 53)) neg = pg.BarGraphItem(x=np.array(neg_x), height=np.array(neg_y), width=0.5, brush=(255, 94, 94)) neutral = pg.BarGraphItem(x=np.array(neu_x), height=np.array(neu_y), width=0.5, brush=(232, 255, 248)) graphView.addItem(pos) graphView.addItem(neg) graphView.addItem(neutral) prev += 2 graphView.hideAxis('bottom') graphView.plot()
def init_ui(self): """""" pg.setConfigOptions(antialias=True) # Create plot widgets self.close_plot = self.addPlot( title="收盘价格", axisItems={"bottom": DateAxis(self.dates, orientation="bottom")}) self.nextRow() self.balance_plot = self.addPlot( title="账户净值", axisItems={"bottom": DateAxis(self.dates, orientation="bottom")}) self.nextRow() self.drawdown_plot = self.addPlot( title="净值回撤", axisItems={"bottom": DateAxis(self.dates, orientation="bottom")}) self.nextRow() self.pnl_plot = self.addPlot( title="每日盈亏", axisItems={"bottom": DateAxis(self.dates, orientation="bottom")}) self.nextRow() self.distribution_plot = self.addPlot(title="盈亏分布") # Add curves and bars on plot widgets self.close_curve = self.close_plot.plot( pen=pg.mkPen("#afd0a7", width=3)) self.balance_curve = self.balance_plot.plot( pen=pg.mkPen("#ffc107", width=3)) dd_color = "#303f9f" self.drawdown_curve = self.drawdown_plot.plot(fillLevel=-0.3, brush=dd_color, pen=dd_color) profit_color = 'r' loss_color = 'g' self.profit_pnl_bar = pg.BarGraphItem(x=[], height=[], width=0.3, brush=profit_color, pen=profit_color) self.loss_pnl_bar = pg.BarGraphItem(x=[], height=[], width=0.3, brush=loss_color, pen=loss_color) self.pnl_plot.addItem(self.profit_pnl_bar) self.pnl_plot.addItem(self.loss_pnl_bar) distribution_color = "#6d4c41" self.distribution_curve = self.distribution_plot.plot( fillLevel=-0.3, brush=distribution_color, pen=distribution_color)
def update_view(self, x, y, z): self.clear() x_ax = np.arange(1) bg1 = pg.BarGraphItem(x=x_ax, height=abs(x), width=0.3, brush='y') bg2 = pg.BarGraphItem(x=x_ax + 0.33, height=abs(y), width=0.3, brush='r') self.addItem(bg1) self.addItem(bg2)
def prepare_plot(self) -> None: """ Method to prepare the plot :return: None """ # If the data array is empty, return if not self.data: return # Calculate the average av = np.average(self.data) # Get the unique elements of data and their counts unique, counts = np.unique(self.data, return_counts=True) # Calculate the occurence probability of all unique elements prob = [counts[x] / np.sum(counts) for x in range(len(counts))] # Calculate the probability of elements to occur according to the poisson distrubution poisson = self.poisson(av, np.arange(0, max(unique))) # Prepare bar graphs self.data_graph = pg.BarGraphItem(x=unique - 0.1, height=prob, width=0.2, brush=pg.mkBrush(color=(255, 50, 30, 255))) self.data_graph_line = pg.PlotDataItem(unique - 0.1, prob, pen=pg.mkPen(color=(255, 50, 30, 100), width=5)) self.poisson_graph = pg.BarGraphItem(x=np.arange(0, max(unique)) + 0.1, height=poisson, width=0.2, brush=pg.mkBrush(color=(85, 30, 255, 255))) self.poisson_graph_line = pg.PlotDataItem( np.arange(0, max(unique)) + 0.1, poisson, pen=pg.mkPen(color=(85, 30, 255, 100), width=5)) self.data_average_line = InfiniteLine(av, angle=90, pen=pg.mkPen(color=(0, 255, 0, 255))) # Add indicator for data average self.addItem(self.data_average_line) # self.addItem(self.data_graph_line) # self.addItem(self.poisson_graph_line) self.addItem(self.poisson_graph) self.addItem(self.data_graph) self.setToolTip( "Red: Data Distribution\nBlue: Poisson Distribution\nGreen: Average" ) # Add Legend # TODO """
def bar(self, X, Y, **kwds): nX, nY = len(X), len(Y) centre = nX == nY widths = np.diff(X).ravel() if centre and nX > 1: widths = np.hstack((widths, widths[-1])) if centre: self.barchart = pg.BarGraphItem(x=X, height=Y, width=widths, **kwds) else: self.barchart = pg.BarGraphItem(x0=X, height=Y, width=widths, **kwds) self.view.addItem(self.barchart) return self.barchart
def countingSort(self, arr, maxRange): x = [] n = len(arr) self.progressBar.setMaximum(n - 1) for lel in range(1, n + 1): x.append(lel) # The output character array that will have sorted arr output = [0] * maxRange # Create a count array to store count of inidividul # characters and initialize count array as 0 count = [0] * maxRange # For storing the resulting answer since the # string is immutable # ans = [0] * len(arr) ans = numpy.random.randint(0, 1, len(arr)) # Store count of each character for i in arr: count[i] += 1 # Change count[i] so that count[i] now contains actual # position of this character in output array for i in range(maxRange): count[i] += count[i - 1] # Build the output character array for i in range(len(arr)): output[count[arr[i]] - 1] = arr[i] count[arr[i]] -= 1 # Copy the output array to arr, so that arr now # contains sorted characters for i in range(len(arr)): if self.checkBoxStop.isChecked(): while self.checkBoxStop.isChecked() == 1: QtTest.QTest.qWait(50) else: speed = (4000 - (self.horizontalSliderSpeed.value()) * 1000) / 2 QApplication.processEvents() QtTest.QTest.qWait(speed) self.graphicsViewVisualize.clear() bg1 = pyqtgraph.BarGraphItem(x=x, height=ans, width=0.3, brush='r') self.graphicsViewVisualize.addItem(bg1) ans[i] = output[i] self.graphicsViewVisualize.clear() bg1 = pyqtgraph.BarGraphItem(x=x, height=ans, width=0.3, brush='r') self.graphicsViewVisualize.addItem(bg1) self.progressBar.setValue(i) return ans
def buttonStatitics(button_num): global b_num, x, y1, y2, y3, y4 if button_num == "1": y1.append(1) bg1 = pg.BarGraphItem(x=x, height=len(y1), width=.4, brush='r') w1.addItem(bg1) elif button_num == "2": y2.append(2) bg2 = pg.BarGraphItem(x=x, height=len(y2), width=.4, brush='g') w1.addItem(bg2) elif button_num == "3": y3.append(3) bg3 = pg.BarGraphItem(x=x, height=len(y3), width=.4, brush='b') w1.addItem(bg3) elif button_num == "4": y4.append(4) bg4 = pg.BarGraphItem(x=x, height=len(y4), width=.4, brush='y') w1.addItem(bg4) elif len(y1) and len(y2) and len(y3) and len(y4) == 0: bg1 = pg.BarGraphItem(x=x, height=0, width=.4, brush='r') bg2 = pg.BarGraphItem(x=x, height=0, width=.4, brush='g') bg3 = pg.BarGraphItem(x=x, height=0, width=.4, brush='b') bg4 = pg.BarGraphItem(x=x, height=0, width=.4, brush='y') w1.addItem(bg1) w1.addItem(bg2) w1.addItem(bg3) w1.addItem(bg4) ui.dockWidget.setWidget(w1) ui.label_8.setText("Button_1:: " + str(len(y1))) ui.label_9.setText("Button_2:: " + str(len(y2))) ui.label_10.setText("Button_3:: " + str(len(y3))) ui.label_11.setText("Button_4:: " + str(len(y4)))
def GraphBar(win,y,c): """ Plot a Bar graphic for each value of y(n array) with its respective color c(n array)""" bg1 = pg.BarGraphItem(x=[0], height=[y[0]], width=0.5, brush=c[0]) bg2 = pg.BarGraphItem(x=[1], height=[y[1]], width=0.5, brush=c[1]) bg3 = pg.BarGraphItem(x=[2], height=[y[2]], width=0.5, brush=c[2]) bg4 = pg.BarGraphItem(x=[3], height=[y[3]], width=0.5, brush=c[3]) win.addItem(bg1) win.addItem(bg2) win.addItem(bg3) win.addItem(bg4) win.getAxis('bottom').setTicks([[(0, 'Delta'), (1, 'Theta'), (2, 'Alpha'), (3, 'Beta')]]) win.setLabel('left', 'Energy', units='%')
def Update_Stats(self, data, display_Bars): """ Calculate mean, max, fwhm of the data between the two markers. Optionally plot bars between the markers of the mean and max values. data should be an np.ndarray, display_Bars a boolean. Returns a tuple (mean, max, fwhm) so the caller can actually do something with them (like display on a GUI?) """ # Get the data between the bars integral_Data = data[self._data_Bins[0]:self._data_Bins[1]] # If there isn't any data (usually this is if the cursor hasn't been # placed yet, or the width is accidentally 0), set everything to zero if len(integral_Data) == 0: mean_Value = 0 max_Value = 0 fwhm_Value = 0 else: # Calculate the values mean_Value = integral_Data.mean() max_Value = integral_Data.max() fwhm_Value = sum( integral_Data > (max_Value / 2)) * self._resolution if display_Bars: # Make some bars objects and add them to the plot widget. self.mean_Bar = pyqtgraph.BarGraphItem( x0=[self._left_Position], x1=[self._right_Position], height=[mean_Value], pen=self._colour, brush=self._colour) self.max_Bar = pyqtgraph.BarGraphItem( x0=[self._left_Position], x1=[self._right_Position], height=[max_Value], pen=self._colour, brush=self._colour_Alpha) self.Add_Bars() else: # If display bars is off, best make sure the bars aren't on # the widget right now. self.Remove_Bars() return mean_Value, max_Value, fwhm_Value
def update_extra(self): all_nan = {'hr_graph': True, 'power_graph': True} for key in all_nan.keys(): chk = np.isnan(self.config.logger.sensor.values['integrated'][key]) if False in chk: all_nan[key] = False if not all_nan['hr_graph']: self.p1.clear() #for HR self.p1.addItem( pg.PlotCurveItem( self.config.logger.sensor.values['integrated']['hr_graph'], pen=self.pen1)) #for Power if not all_nan['power_graph']: self.p2.clear() self.p2.setGeometry(self.p1.vb.sceneBoundingRect()) self.p2.linkedViewChanged(self.p1.vb, self.p2.XAxis) bg = pg.BarGraphItem( x0=self.plot_data_x1[:-1], x1=self.plot_data_x1[1:], height=self.config.logger.sensor.values['integrated'] ['power_graph'], brush=self.brush, pen=self.pen2) self.p2.addItem(bg)
def __init__(self, name, n, freq): super().__init__() layout = QHBoxLayout() self.setWindowTitle(name) color = np.ones((n, 4), dtype=np.float32) color[:, 0] = np.linspace(0, 1, n) color[:, 1] = color[::-1, 0] canvas = scene.SceneCanvas(keys='interactive', show=True) grid = canvas.central_widget.add_grid(spacing=0) self.viewbox = grid.add_view(row=0, col=1, camera='panzoom') x_axis = scene.AxisWidget(orientation='bottom') x_axis.stretch = (1, 0.1) grid.add_widget(x_axis, row=1, col=1) x_axis.link_view(self.viewbox) y_axis = scene.AxisWidget(orientation='left') y_axis.stretch = (0.1, 1) grid.add_widget(y_axis, row=0, col=0) y_axis.link_view(self.viewbox) self.pos = np.zeros((n, 2), dtype=np.float32) self.pos[:, 0] = rfftfreq(n, 1/freq) #pos[:, 0] = self.x_mesh[:self.n_samples_to_display] self.line = scene.Line(self.pos, color, parent=self.viewbox.scene) self.viewbox.camera.set_range() self.freqbar = pg.BarGraphItem(x=[1], height=0, width=0.6, brush='g') self.plot = pg.PlotWidget() self.plot.addItem(self.freqbar) self.plot.setFixedWidth(100) layout.addWidget(canvas.native) layout.addWidget(self.plot) self.setLayout(layout)
def display_bar_graph(widget, x, y, width, brush, title, label): """ :param widget: widget object to draw the graph on it :param x: list of numbers in the x-direction :param y: list of numbers in the y-direction :param width: width of the bar :param brush: color of the bar :param title: title of the window :param label: bottom label of the window :return: """ # Create BarGraphItem and add it to the widget bg = pg.BarGraphItem(x=x, height=y, width=width, brush=brush) widget.addItem(bg) # Adjust Widget widget.plotItem.setTitle(title) widget.plotItem.showGrid(True, True, alpha=0.8) widget.plotItem.setLabel("bottom", text=label) # Auto scale Y Axis vb = widget.getViewBox() vb.setAspectLocked(lock=False) vb.setAutoVisible(y=1.0) vb.enableAutoRange(axis='y', enable=True)
def plot_delays(self): self.preview_plt.clear() if self.delays_chb.isChecked(): bg = pg.BarGraphItem(x=self.ts, height=self.us, width=len(self.sig_x) * (self.sig_x[1] - self.sig_x[0]), brush='r') self.preview_plt.addItem(bg) self.preview_plt.plot()
def show(tune): import pyqtgraph as pg plt = pg.plot() plt.addLine(y=0) plt.addLine(y=12) plt.addLine(x=0) ticks = [] for i in (0, 1): for pitch in "CDEFGAB": ticks.append((i * 12 + pitch_values[pitch], pitch)) plt.getAxis('left').setTicks([ticks]) tvals = [] yvals = [] t = 0 for token in tune.tokens: if isinstance(token, Beam): plt.addLine(x=t) elif isinstance(token, Note): tvals.append(t) yvals.append(token.pitch.abs_value) t += token.duration plt.plot(tvals, yvals, pen=None, symbol='o') hist = tune.pitchogram() k = sorted(hist.keys()) v = [hist[x] for x in k] plt = pg.plot() bar = pg.BarGraphItem(x=k, height=v, width=1) plt.addItem(bar) plt.getAxis('bottom').setTicks([ticks])
def plotBarGraphItem(self, name, lstX=[], lstY=[]): if len(lstX) == 0: return pg.PlotItem(title=name) ticklist = [] ix = [] i = 0 p = pg.PlotItem(title=name) for x in lstX: ticklist.append((i, x)) ix.append(i) if lstY[i] > 0: k = 0.5 else: k = 0 text = pg.TextItem( html= '<div style="text-align: center"><span style="color: #FFF;">' + "%.1f" % (lstY[i]) + '</span><br></div>', anchor=(0.5, k), angle=0) p.addItem(text) text.setPos(i, lstY[i]) i = i + 1 bg1 = pg.BarGraphItem(x=ix, height=lstY, width=0.3, brush='r') p.addItem(bg1) p.getAxis("bottom").setTicks([ticklist, []]) return p