def updateGraph(self, event=None): ### GRAPH DRAWING timestamps, values = self.dataManager.getGraphData( self.selection.get()) timestampsMap = matplotlib.dates.date2num(timestamps) x = np.array(timestampsMap) y = np.array(values) fig = Figure(figsize=(20, 15)) a = fig.add_subplot(111) a.plot(x, y, color='blue', linewidth=1) # a.invert_yaxis() a.set_title("Graph of " + self.selection.get(), fontsize=16) a.set_ylabel("Value", fontsize=14) a.set_xlabel("Time", fontsize=14) a.set_xlim([min(x) - 0.1, max(x) + 0.1]) myFmt = matplotlib.dates.DateFormatter("%d.%m. %H:%M") fig.gca().xaxis.set_major_formatter(myFmt) if self.canvas is not None: self.canvas.get_tk_widget().destroy() self.canvas = FigureCanvasTkAgg(fig, master=self.window) self.canvas.get_tk_widget().grid(row=2, column=1, rowspan=len( self.sensorStatusesLabels)) self.canvas.draw()
class Plot(object): def __init__(self): self.fig = Figure() self.canvas = FigureCanvas(self.fig) self.ax = self.fig.add_subplot(111) self.width, self.height = None, None self.xlim = [None, None] self.ylim = [None, None] self.xticks, self.yticks = None, None self.axeslabels = ['seq1', 'seq2'] self.title = '' def render(self): #title = 'THREAT plot for seq1 and seq2' if self.title: self.ax.set_title(self.title) else: self.ax.set_title('unnamed plot') self.fig.gca().invert_yaxis() def save(self, filename, dpi=80, format='png'): self.fig.savefig(filename, dpi=dpi, format=format)
class PlotWidget(QtWidgets.QWidget): ''' classdocs ''' __figure__ = None __canvas__ = None def __init__(self): ''' Constructor ''' super().__init__() self.setLayout(QtWidgets.QVBoxLayout(self)) self.__figure__ = Figure() self.__canvas__ = FigureCanvas(self.__figure__) #This next line works for when Axes are created, but not when the axis imshow is called self.__figure__.add_axobserver(lambda x: self.__canvas__.draw_idle()) self.layout().addWidget(self.__canvas__) self.layout().setMenuBar(NavigationToolbar2QT(self.__canvas__, self)) def get_figure(self): return self.__figure__ def get_canvas(self): return self.__canvas__ def imshow(self, *args, **kwargs): self.__figure__.gca().imshow(*args, **kwargs) self.__canvas__.draw_idle()
class Matplot(object): def __init__(self): # 新建一个Figure self.figure = Figure() # 将Figure转换为Qt4 Widget控件以便插入Qt4界面 self.canvas = FigureCanvas(self.figure) def _change(self, _list1,_list2,_list3): # self.figure.clear() self.x = range(100) # y = [100]*100 # y = [0]*100 self.ax.clear() self.ax.plot(self.x,_list1,"y-",linewidth=3,label='Light(lx)') self.ax.plot(self.x,_list2,"m-",linewidth=3,label='Tempure(℃)') self.ax.plot(self.x,_list3,"c-",linewidth=3,label='Humid(%RH)') #设置图例 self.ax.legend(loc='upperright') # 显示图例,loc设置图例位置 # ax.set_subplots_adjust(bottom = 0.15) # self.ax.show() # self.figure.suptitle("F3 fata diagram") self.canvas.draw() def set_diagram(self,n): self.ax = self.figure.add_subplot(111) #设置坐标轴范围 self.ax.set_xlim((0, 110)) self.ax.set_ylim((0, 150)) #设置坐标轴刻度 my_x_ticks = np.arange(0,110, 10) my_y_ticks = np.arange(0, 150, 10) ymajorLocator = MultipleLocator(10) self.ax.set_xticks(my_x_ticks) self.figure.gca().invert_xaxis() # self.figure.gca().invert_xticks() self.ax.set_yticks(my_y_ticks) self.ax.yaxis.set_major_locator(ymajorLocator) self.ax.set_xticklabels(('220s','200s','180s','160s','140s','120s','100s','80s','60s','40s','20s')) self.figure.subplots_adjust(left=0.05, bottom=0.07, right=0.97, top=0.93,hspace=0.2, wspace=0.2) self.ax.set_title('F'+str(n)+'节点数据折线图',fontproperties='SimHei',fontsize=14) self.canvas.draw()
class DoseReport(QtGui.QMainWindow): def __init__(self, vois, parent=None): super(DoseReport, self).__init__(parent) self.figure = Figure() # don't use matplotlib.pyplot at all! self.canvas = FigureCanvas(self.figure) # use addToolbar to add toolbars to the main window directly! self.toolbar = NavigationToolbar(self.canvas, self) self.addToolBar(self.toolbar) self.main_widget = QtGui.QWidget(self) self.setCentralWidget(self.main_widget) layout = QtGui.QVBoxLayout() layout.addWidget(self.canvas) self.main_widget.setLayout(layout) self.plot(vois) def plot(self, vois): # create an axis ax = self.figure.add_subplot(111) # Tweak axes: ax.grid(True) ax.set_title('Dose Volume histograms') ax.set_xlabel('Dose (mGy)') ax.set_ylabel('Volume (% of total)') # ...Create the formatter using the function to_percent. This multiplies all the # default labels by 100, making them all percentages # (from http://matplotlib.org/examples/pylab_examples/histogram_percent_demo.html) formatter = FuncFormatter(self.to_percent) self.figure.gca().yaxis.set_major_formatter(formatter) # don't repaint at each plot call ax.hold(True) # plot data for v in vois: l = str(v.label) print "-->", l ax.hist(v.doses().values(), normed=True, cumulative=-1, histtype='step', label=l) # refresh canvas ax.legend(loc='lower left') self.canvas.draw() def to_percent(self, y, position): # Ignore the passed in position. This has the effect of scaling the default # tick locations. s = str(100 * y) # The percent symbol needs escaping in latex if matplotlib.rcParams['text.usetex'] is True: return s + r'$\%$' else: return s + '%'
def __init__(self, parent, grid, count, vmin=None, vmax=None, legend=None, codim=1, separate_plots=False, dpi=100): assert isinstance(grid, OnedGrid) assert codim in (0, 1) figure = Figure(dpi=dpi) if not separate_plots: axes = figure.gca() axes.hold(True) self.codim = codim lines = () centers = grid.centers(1) if grid._identify_left_right: centers = np.concatenate((centers, [[grid._domain[1]]]), axis=0) self.periodic = True else: self.periodic = False if codim == 1: xs = centers else: xs = np.repeat(centers, 2)[1:-1] for i in range(count): if separate_plots: figure.add_subplot(int(count / 2) + count % 2, 2, i + 1) axes = figure.gca() pad = (vmax[i] - vmin[i]) * 0.1 axes.set_ylim(vmin[i] - pad, vmax[i] + pad) l, = axes.plot(xs, np.zeros_like(xs)) lines = lines + (l, ) if legend and separate_plots: axes.legend([legend[i]]) if not separate_plots: pad = (max(vmax) - min(vmin)) * 0.1 axes.set_ylim(min(vmin) - pad, max(vmax) + pad) if legend: axes.legend(legend) self.lines = lines super().__init__(figure) self.setParent(parent) self.setMinimumSize(300, 300) self.setSizePolicy( QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
class MplCanvas( FigureCanvas ): def __init__( self, parent = None ): self.fig = Figure( figsize = ( 5, 5 ), dpi = 100, tight_layout = True ) self.fig.gca().set_aspect( 'equal', adjustable = 'box' ) self.axes = self.fig.add_subplot( 111 ) self.axes.axis( 'off' ) FigureCanvas.__init__( self, self.fig ) self.setParent( parent ) FigureCanvas.setSizePolicy( self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding ) FigureCanvas.updateGeometry( self ) self.img = self.axes.imshow( np.zeros( ( 100, 100 ) ), cmap = 'gray', origin = 'lower' )
def prepare(self, *figargs, **figkwargs): fig = Figure(*figargs, **figkwargs) fig.gca().invert_yaxis() subplot = fig.add_subplot(111) subplot.set_ylabel('Depth') subplot.set_xlabel('Time') xfmt = ticker.FuncFormatter(lambda s, _: '%02d:%02d' % (int(s) / 60, s % 60)) subplot.xaxis.set_major_formatter(xfmt) for profile in self.profiles: subplot.plot(profile.times, profile.depths, label=profile.label) subplot.legend() return fig
def order_gen_data(user_id, images_id): global data_object X_plot = [] Y_plot = [] datetime_object = datetime.datetime.now() user_labled = db.child('Labeled_Images').get().val() user_name = db.child('data/users/' + user_id + '/' + 'name').get().val() user_images_data = db.child('Labeled_Images/' + user_id).get().val() if user_id in user_labled: if images_id in user_images_data: images_data = db.child('Labeled_Images/' + user_id + '/' + images_id).get().val() for set_of_points in images_data: position = set_of_points['points'] for pos in position: x_data = pos['x'] X_plot.append(x_data) y_data = pos['y'] Y_plot.append(y_data) fig = Figure() ax = fig.add_subplot(1, 1, 1) plt.style.use('dark_background') ax.scatter(X_plot, Y_plot, color='white', s=10) x0, x1 = ax.get_xlim() y0, y1 = ax.get_ylim() ax.set_aspect(abs(x1 - x0) / abs(y1 - y0)) fig.gca().invert_yaxis() ax.set_facecolor('xkcd:black') ax.axis('off') canvas = FigureCanvas(fig) png_output = BytesIO() canvas.print_png(png_output) data = b64encode(png_output.getvalue()).decode('ascii') datetime_object = str(datetime_object) data_url = data data_object = { 'TimeStamped': datetime_object, 'Images_data': data_url, 'Labeled By': user_name, 'DataType': 'image/png;base64' } db.child('Generated_Labeled_Images/' + user_id + '/' + images_id).set(data_object) return jsonify({'Data_generated': data_object}), 201 else: return jsonify({'message': 'Not found your data!'}), 404 else: return jsonify({'message': 'Not found a user!'}), 403
class Matplotlib1DWidget(FigureCanvas): def __init__(self, parent, grid, count, vmin=None, vmax=None, legend=None, codim=1, dpi=100): assert grid.reference_element is line assert codim in (0, 1) self.figure = Figure(dpi=dpi) self.axes = self.figure.gca() self.axes.hold(True) lines = tuple() for _ in xrange(count): l, = self.axes.plot(grid.centers(codim), np.zeros_like(grid.centers(codim))) lines = lines + (l,) self.axes.set_ylim(vmin, vmax) if legend: self.axes.legend(legend) self.lines = lines super(Matplotlib1DWidget, self).__init__(self.figure) self.setParent(parent) self.setMinimumSize(300, 300) self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) def set(self, U, ind): for line, u in izip(self.lines, U): line.set_ydata(u[ind]) self.draw()
class SunPyPlot(FigureCanvas): """SunPy preview image""" def __init__(self, map_, width, height, parent=None, dpi=100, **matplot_args): # pylint: disable=W0613 # self._widthHint = width # self._heightHint = height self._origMap = map_ self._map = map_.resample((width, height)) # Old way (segfaults in some environements) # self.figure = self._map.plot_simple(**matplot_args) # FigureCanvas.__init__(self, self.figure) self.figure = Figure() self._map.plot(figure=self.figure, basic_plot=True, **matplot_args) self.axes = self.figure.gca() FigureCanvas.__init__(self, self.figure) # How can we get the canvas to preserve its aspect ratio when expanding? # sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) # sizePolicy.setHeightForWidth(True) # self.setSizePolicy(sizePolicy) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) self.setSizePolicy(sizePolicy) self.setMinimumSize(QtCore.QSize(width, height)) self.setMaximumSize(QtCore.QSize(width, height))
def preprocess(self, low=0.32, high=2.55, UV=0, fit_order=1, idx_in=3): plt.close('all') # hack! low, high, UV = float(low), float(high), float(UV) self.pp_bounds = (low, high, UV) fit_order = int(fit_order) idx_in = int(idx_in) if self.hapke_scalar.needs_isow: # initialize isow as a scalar isoind1, isoind2 = np.searchsorted(self.calspec[:, 0], (low, high)) self.hapke_scalar.set_isow(self.calspec[isoind1:isoind2, 1].mean()) # run preprocessing on each spectrum for key, traj in self.spectra.items(): self.pp_spectra[key] = analysis.preprocess_traj( traj, low, high, UV, fit_order=fit_order, idx=idx_in) # plot the results fig = Figure(figsize=(6, 4), frameon=False, tight_layout=True) ax = fig.gca() #If additional files exist we plot them for k in self.pp_spectra: ax.plot(*self.pp_spectra[k].T, label=k) ax.legend(fontsize='small', loc='best') ax.set_title('Preprocessed spectra') ax.set_xlabel('Wavelength ($\mu{}m)$') ax.set_ylabel('Reflectance') #pp is the parameter used for identifying the download data. return 'Preprocessing complete: ', 'pp', [fig]
class SHistogram(tk.Frame): def __init__(self, controller): tk.Frame.__init__(self, controller) def generateGraph(self, x, y, xAxis, yAxis, xticks=1): self.graphInitialization() self.showGraph(x, y, xAxis, yAxis, xticks) def graphInitialization(self): self.f = Figure(figsize=(4, 5), dpi=100) self.canvas = FigureCanvasTkAgg(self.f, self) self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True) def showGraph(self, bins, y, xAxis, yAxis, xticks=1): self.p = self.f.gca() oldBins = bins N, bins, patches = self.p.hist(y, bins=bins) fracs = N / N.max() norm = colors.Normalize(fracs.min(), fracs.max()) for thisfrac, thispatch in zip(fracs, patches): color = plt.cm.viridis(norm(thisfrac)) thispatch.set_facecolor(color) self.p.set_xlabel(xAxis, fontsize=15) self.p.set_ylabel(yAxis, fontsize=15) self.p.set_xticks(range(0, max(y), int(xticks))) loc = matplotlib.ticker.MultipleLocator( base=1) # this locator puts ticks at regular intervals self.p.yaxis.set_major_locator( loc) #we don't want to count freq to determine y max self.canvas.draw()
def compute_metrics(result_file, gt_file): # groundtruth with open(gt_file, 'r', newline='') as csv_file: reader = csv.reader(csv_file, delimiter=',') gt = [int(row[1]) for row in reader] # prediction pred = [] i = 0 with open(result_file, 'r', newline='') as csv_file: reader = csv.reader(csv_file, delimiter=',') for row in reader: prob = list(map(float, row)) pred.append(prob[1]) i += 1 # compute mAP mAP = average_precision_score(gt, pred, average='macro') # compute AUC AUC = roc_auc_score(gt, pred) # plot ROC curve precision, recall, __ = precision_recall_curve(gt, pred, pos_label=1) fig = Figure() canvas = FigureCanvasAgg(fig) ax = fig.gca() ax.step(recall, precision, color='b', alpha=0.2, where='post') ax.fill_between(recall, precision, step='post', alpha=0.2, color='b') ax.set_xlabel('Recall') ax.set_ylabel('Precision') ax.set_ylim([0.0, 1.05]) ax.set_xlim([0.0, 1.0]) canvas.draw() I = np.fromstring(canvas.tostring_rgb(), dtype='uint8', sep='') I = I.reshape(canvas.get_width_height()[::-1]+(3,)) I = np.transpose(I, [2,0,1]) return mAP, AUC, torch.Tensor(np.float32(I))
def plot_parameter_curve(mcmc_set, p_index, p_name): # Make sure we've already run the fits for this mcmc set! if mcmc_set.name not in two_exp_fits_dict.keys(): raise Exception('%s not found in two_exp_fits_dict!' % mcmc_set.name) # Make sure we've already run the fits for the data! if 'data' not in two_exp_fits_dict.keys(): fit_data(mcmc_set) # Get the parameter array p_arr = two_exp_fits_dict[mcmc_set.name][p_index] p_arr_data = two_exp_fits_dict['data'][p_index] data = mcmc_set.chains[0].data plot_filename = '%s_%s_curve.png' % (mcmc_set.name, p_name) thumbnail_filename = '%s_%s_curve_th.png' % (mcmc_set.name, p_name) # Plot of parameter fig = Figure() ax = fig.gca() ax.plot(data.columns, p_arr, 'b') ax.plot(data.columns, p_arr_data, marker='o', linestyle='', color='r') ax.set_ylabel('%s value' % p_name) ax.set_xlabel('[Bax] (nM)') ax.set_title('%s for %s' % (mcmc_set.name, p_name)) canvas = FigureCanvasAgg(fig) fig.set_canvas(canvas) fig.savefig(plot_filename) fig.savefig(thumbnail_filename, dpi=10) return ThumbnailResult(thumbnail_filename, plot_filename)
def grafica_normal(self): try: semilla = self.bin mu = self.mediana() sigma = self.desviacion_estandar() normal = ss.norm(mu, sigma) # CALCULO DE LA NORMAL fp = normal.pdf(semilla) # REALIZANDO UNA FUNCIÓN DE PROBABILIDAD plt.plot(semilla, fp, color='red') plt.title('Distribución Normal') plt.xlabel('Tamaño') plt.ylabel('Distribución') plt.savefig("docs/normal.png", bbox_inches='tight') # GURDAMOS LA GRAFICA COMO IMAGEN TIPO .PNG winGN = tk.Tk() winGN.wm_title("Gráfica de la distribución normal") fig = Figure(figsize=(5, 4), dpi=100) # fig.add_subplot(111).plot(semilla, fp, color='red') canvas = FigureCanvasTkAgg(fig, master=winGN) canvas.get_tk_widget().grid(row=0, column=0, rowspan=6) p = fig.gca() p.plot(semilla, fp, color='red') # CREACIÓN DE LA GRAFICA p.set_xlabel('Tamaño') p.set_ylabel('Distribución') p.set_title("Distribución Normal") canvas.draw() bot = tk.Button(winGN, text='Cerrar', command=winGN.destroy) bot.grid(row=7, column=0) except(AttributeError): mb.showerror('Error', "No se puede dibujar la gráfica, datos incorrectos")
def display_fig(self, predicted_class, freqs, amplitudes): # Display image img_name = '../figures/' + config.names[predicted_class - 1] + '.png' self.lblImage.setPixmap(QtGui.QPixmap(img_name)) self.lblImage.show() # Display plot scene = QtWidgets.QGraphicsScene() figure = Figure() axes = figure.gca() axes.set_title("SSVEP channel spectra") axes.set_xlabel('Frequencies [Hz]') axes.set_ylabel('Amplitudes') subset_fq = (freqs > 2) & (freqs <= 25) axes.autoscale(True) axes.plot(freqs[subset_fq], amplitudes[subset_fq]) # Show vertical lines corresponding to frequencies for i in range(0, len(config.frequencies)): axes.axvline(x=config.frequencies[i], color='r', alpha=0.5) axes.text(config.frequencies[i], max(amplitudes[subset_fq]) * 0.75, config.names[i], rotation=90, color='r', verticalalignment='bottom') canvas = FigureCanvas(figure) scene.addWidget(canvas) self.gvPlots.setScene(scene)
class PlotPlotPanel(wx.Panel): def __init__(self, parent, dpi=None, **kwargs): wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, **kwargs) self.ztv_frame = self.GetTopLevelParent() self.figure = Figure(dpi=None, figsize=(1.,1.)) self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.Bind(wx.EVT_SIZE, self._onSize) self.axes_widget = AxesWidget(self.figure.gca()) self.axes_widget.connect_event('motion_notify_event', self.on_motion) self.plot_point = None def on_motion(self, evt): if evt.xdata is not None: xarg = np.abs(self.ztv_frame.plot_panel.plot_positions - evt.xdata).argmin() ydata = self.ztv_frame.plot_panel.plot_im_values[xarg] self.ztv_frame.plot_panel.cursor_position_textctrl.SetValue('{0:.6g},{1:.6g}'.format(evt.xdata, ydata)) if self.plot_point is None: self.plot_point, = self.axes.plot([evt.xdata], [ydata], 'xm') else: self.plot_point.set_data([[evt.xdata], [ydata]]) self.figure.canvas.draw() def _onSize(self, event): self._SetSize() def _SetSize(self): pixels = tuple(self.GetClientSize()) self.SetSize(pixels) self.canvas.SetSize(pixels) self.figure.set_size_inches(float(pixels[0])/self.figure.get_dpi(), float(pixels[1])/self.figure.get_dpi())
def preprocess(self, low=0.32, high=2.55, UV=0, fit_order=1, idx_in=3): plt.close('all') # hack! low, high, UV = float(low), float(high), float(UV) self.pp_bounds = (low, high, UV) fit_order = int(fit_order) idx_in = int(idx_in) if self.hapke_scalar.needs_isow: # initialize isow as a scalar isoind1, isoind2 = np.searchsorted(self.calspec[:,0], (low, high)) self.hapke_scalar.set_isow(self.calspec[isoind1:isoind2,1].mean()) # run preprocessing on each spectrum for key, traj in self.spectra.items(): self.pp_spectra[key] = analysis.preprocess_traj(traj, low, high, UV, fit_order=fit_order, idx = idx_in) # plot the results fig = Figure(figsize=(6, 4), frameon=False, tight_layout=True) ax = fig.gca() #If additional files exist we plot them for k in self.pp_spectra: ax.plot(*self.pp_spectra[k].T, label=k) ax.legend(fontsize='small', loc='best') ax.set_title('Preprocessed spectra') ax.set_xlabel('Wavelength ($\mu{}m)$') ax.set_ylabel('Reflectance') #pp is the parameter used for identifying the download data. return 'Preprocessing complete: ', 'pp', [fig]
def get_bar_plot_np(counts, t=10, label=''): x = np.arange(len(counts)) x1 = x[::-1] * (-t) xlab = np.array(["{}s".format(i) for i in x1]) xlab[-1] = 'NOW' if len(counts) > 7: xlab[::2] = '' fig = Figure(figsize=(3.0, 1.8)) canvas = FigureCanvas(fig) ax = fig.gca() ax.bar(x, counts) ax.set_facecolor('#c8c8c8') ax.set_xticks(x) ax.set_xticklabels(xlab) #, rotation=30) #ax.axis('off') w, h = canvas.get_width_height() ax.set_title(label) canvas.draw() # draw the canvas, cache the renderer np_img = np.fromstring(canvas.tostring_rgb(), dtype='uint8') np_img = np_img.reshape((h, w, 3)) return np_img
def plot_histogram(data, xlabel="", ylabel="", title=""): assert isinstance(data, list) # Preset fig = Figure(figsize=(5, 4), dpi=150) canvas = FigureCanvas(fig) ax = fig.gca() # Plot ax.hist(data, bins=20, rwidth=0.9, zorder=3) # Axes ax.grid(color="0.95", zorder=0) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.set_title(title) fig.tight_layout(pad=2) # Return numpy array canvas.draw() image_from_plot = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) image_from_plot = image_from_plot.reshape( fig.canvas.get_width_height()[::-1] + (3,) ) return image_from_plot
def generate_scatterplot(datafname, imgfname): """Creates a 2D scatter plot of the specified Gocator XYZ data and saves it in the specified image filename.""" matplotlib.rcParams['axes.formatter.limits'] = -4, 4 matplotlib.rcParams['font.size'] = 14 matplotlib.rcParams['axes.titlesize'] = 12 matplotlib.rcParams['axes.labelsize'] = 12 matplotlib.rcParams['xtick.labelsize'] = 11 matplotlib.rcParams['ytick.labelsize'] = 11 figure = Figure() canvas = FigureCanvas(figure) axes = figure.gca() x,y,z = np.genfromtxt(datafname, delimiter=",", unpack=True) xi = x[z!=-32.768] yi = y[z!=-32.768] zi = z[z!=-32.768] scatter_plt = axes.scatter(xi, yi, c=zi, cmap=cm.get_cmap("Set1"), marker=',') axes.grid(True) axes.axis([np.min(xi), np.max(xi), np.min(yi), np.max(yi)]) axes.set_title(os.path.basename(datafname)) colorbar = figure.colorbar(scatter_plt) colorbar.set_label("Range [mm]") axes.set_xlabel("Horizontal Position [mm]") axes.set_ylabel("Scan Position [mm]") figure.savefig(imgfname)
def tBidBax_kd(mcmc_set): """ .. todo:: document the basis for this""" num_kds = 10000 # Get indices for the tBid/Bax binding constants estimate_params = mcmc = mcmc_set.chains[0].options.estimate_params tBid_iBax_kf_index = None tBid_iBax_kr_index = None for i, p in enumerate(estimate_params): if p.name == 'tBid_iBax_kf': tBid_iBax_kf_index = i elif p.name == 'tBid_iBax_kr': tBid_iBax_kr_index = i # If we couldn't find the parameters, return None for the result if tBid_iBax_kf_index is None or tBid_iBax_kr_index is None: return Result(None, None) # Sample the kr/kf ratio across the pooled chains kd_dist = np.zeros(num_kds) for i in range(num_kds): position = mcmc_set.get_sample_position() kd_dist[i] = ((10 ** position[tBid_iBax_kr_index]) / (10 ** position[tBid_iBax_kf_index])) # Calculate the mean and variance mean = kd_dist.mean() sd = kd_dist.std() # Plot the Kd distribution plot_filename = '%s_tBidiBax_kd_dist.png' % mcmc_set.name fig = Figure() ax = fig.gca() ax.hist(kd_dist) canvas = FigureCanvasAgg(fig) fig.set_canvas(canvas) fig.savefig(plot_filename) return MeanSdResult(mean, sd, plot_filename)
class Histogram(tk.Toplevel): def __init__(self, master, name, data): tk.Toplevel.__init__(self, master) self.wm_title("Histogram: {}".format(name)) self.fig = Figure(figsize=(4,3), dpi=100) canvas = FigureCanvasTkAgg(self.fig, self) canvas.get_tk_widget().pack(fill=tk.BOTH, expand=1) toolbar = NavigationToolbar2TkAgg(canvas, self) menubar = tk.Menu(self) menubar.add_command(label="Save Data", command=self.save) self.config(menu=menubar) ax = self.fig.gca() ax.set_title(name) self.hist, self.bins, _ = ae.hist(data, ax=ax, density=True) self.update() def save(self): from numpy import savetxt, transpose fname = tkFileDialog.asksaveasfilename(parent=self, filetypes=[('Data file', '.txt .dat')]) if fname: savetxt(fname, transpose([self.bins[:-1], self.bins[1:], self.hist]))
class CDF(tk.Toplevel): def __init__(self, master, name, data): tk.Toplevel.__init__(self, master) self.wm_title("CDF: {}".format(name)) self.fig = Figure(figsize=(4,3), dpi=100) canvas = FigureCanvasTkAgg(self.fig, self) canvas.get_tk_widget().pack(fill=tk.BOTH, expand=1) toolbar = NavigationToolbar2TkAgg(canvas, self) menubar = tk.Menu(self) menubar.add_command(label="Save Data", command=self.save) self.config(menu=menubar) ax = self.fig.gca() ax.set_title(name) self.x, self.y = ae.cdf(data) ax.plot(self.x, self.y, "o") ax.loglog() ax.grid(True) self.update() def save(self): from numpy import savetxt, transpose fname = tkFileDialog.asksaveasfilename(parent=self, filetypes=[('Data file', '.txt .dat')]) if fname: savetxt(fname, transpose([self.x, self.y]))
def acf_of_ml_residuals(mcmc_set): # Get the maximum likelihood parameters try: (max_likelihood, max_likelihood_position) = mcmc_set.maximum_likelihood() except NoPositionsException as npe: return Result(None, None) # Get the residuals residuals = mcmc_set.chains[0].get_residuals(max_likelihood_position) # Plot the autocorrelation function acf = np.correlate(residuals[1], residuals[1], mode='full') plot_filename = '%s_acf_of_ml_residuals.png' % mcmc_set.name thumbnail_filename = '%s_acf_of_ml_residuals_th.png' % mcmc_set.name fig = Figure() ax = fig.gca() ax.plot(acf) ax.set_title('Autocorrelation of Maximum Likelihood Residuals') canvas = FigureCanvasAgg(fig) fig.set_canvas(canvas) fig.savefig(plot_filename) fig.savefig(thumbnail_filename, dpi=10) return ThumbnailResult(thumbnail_filename, plot_filename)
def get_virtual_drone(): fig_scale = 1 fig = Figure(figsize=(4 * fig_scale, 3 * fig_scale), dpi=200) canvas = FigureCanvas(fig) ax = fig.gca(projection='3d') ax.set_title("Drone Position (meters)") ax.set_ylim([-0.7, 0.7]) ax.set_xlim([-0.7, 0.7]) ax.set_zlim([0, 1]) color = "#00ff00" quiver_color = "#0055ff" if d_pos != None: ax.scatter([d_pos['x']], [d_pos['y']], [d_pos['z']], color=color) if d_vel != None: ax.quiver(d_pos['x'], d_pos['y'], d_pos['z'], d_vel['x'], d_vel['y'], d_vel['z'], length=0.2, color=quiver_color) canvas.draw() width, height = fig.get_size_inches() * fig.get_dpi() image = np.fromstring(canvas.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3) return image
class Render(object): def __init__(self, figsize=(15, 15), dpi=48): self.figsize = figsize self.dpi = dpi self.fig = Figure(figsize=figsize, dpi=dpi) self.canvas = FigureCanvas(self.fig) self.artists = [] def add_artist(self, artist): self.artists.append(artist) def new_frame(self): self.fig.clear() self.ax = self.fig.gca() self.ax.clear() for artist in self.artists: artist.remove() self.artists = [] self.ax.set_xlim(-0.1, MAP_SIZE + 1.1) self.ax.set_ylim(-0.1, MAP_SIZE + 1.1) self.ax.axis('off') def draw(self): for artist in self.artists: self.ax.add_artist(artist) self.canvas.draw() # draw the canvas, cache the renderer width, height = self.fig.get_size_inches() * self.fig.get_dpi() image = np.frombuffer(self.canvas.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3) return image
def make_figure_graphics_item(scene, z=0, static=True): """Creates a FigureCanvas and adds it to the given scene. Used for creating heatmaps and associated colorbars. Args: scene (QGraphicsScene) z (int, optional): z value. Defaults to 0. static (bool, optional): if True (the default) the figure canvas is not movable Returns: QGraphicsProxyWidget: the graphics item that represents the canvas Figure: the figure in the canvas """ figure = Figure(tight_layout={"pad": 0}) axes = figure.gca(xmargin=0, ymargin=0, frame_on=None) axes.get_xaxis().set_visible(False) axes.get_yaxis().set_visible(False) canvas = FigureCanvas(figure) if static: proxy_widget = scene.addWidget(canvas) proxy_widget.setAcceptedMouseButtons(Qt.NoButton) else: proxy_widget = scene.addWidget(canvas, Qt.Window) proxy_widget.setZValue(z) return proxy_widget, figure
class Plot: def __init__(self, size, pos, x_label, x, y_label, y, title): self.x_series = x self.x_label = x_label self.y_label = y_label self.y_series = y self.title = title self.size = size self.pos = pos self.fig = Figure() self.figure = [] def draw(self, window): canvas = FigureCanvas(self.fig) ax = self.fig.gca() ax.plot(self.x_series, self.y_series) ax.set_xlabel(self.x_label) ax.set_ylabel(self.y_label) ax.set_title(self.title) ax.grid(True) canvas.draw() # draw the canvas, cache the renderer width, height = self.fig.get_size_inches() * self.fig.get_dpi() self.figure = np.fromstring(canvas.tostring_rgb(), dtype='uint8').reshape( int(height), int(width), 3) self.figure = cv2.resize(self.figure, flip(self.size)) window[self.pos[0]:self.pos[0] + self.size[0], self.pos[1]:self.pos[1] + self.size[1], :] = self.figure
class ConfuisionMatrix(FigureCanvas): def __init__(self, parent=None, width=5, height=5, back_color="#eeefef"): self.fig = Figure(figsize=(width, height), dpi=100) self.fig.patch.set_facecolor(back_color) FigureCanvas.__init__(self, self.fig) FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.data = None self.values = None self.labels = None self.colors = None def plot(self, labels, colors, values): N = len(labels) ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars: can also be len(x) sequence plots = [] ax = self.fig.gca() ax.set_facecolor("#eeefef") for v in values: p = ax.barh(ind, v, height=0.35) plots.append(p) ax.set_yticks(ind) ax.set_yticklabels(labels) self.fig.subplots_adjust(top=1, wspace=0)
def profile(self, data_file, img_file): """Produces a basic plot of the specified data file, saved as PNG to specified image file.""" matplotlib.rcParams['axes.formatter.limits'] = -4, 4 matplotlib.rcParams['font.size'] = 9 matplotlib.rcParams['axes.titlesize'] = 9 matplotlib.rcParams['axes.labelsize'] = 9 matplotlib.rcParams['xtick.labelsize'] = 8 matplotlib.rcParams['ytick.labelsize'] = 8 figure = Figure() canvas = FigureCanvas(figure) axes = figure.gca() x, y, z = np.genfromtxt(data_file, delimiter=",", unpack=True) xi = x[z > -20] yi = y[z > -20] zi = z[z > -20] scatter_plt = axes.scatter(xi, yi, c=zi, marker="+", cmap=cm.get_cmap("Set1")) axes.grid(True) axes.axis([np.min(xi), np.max(xi), np.min(yi), np.max(yi)]) colorbar = figure.colorbar(scatter_plt) colorbar.set_label("Range [mm]") axes.set_xlabel("Horizontal Position [mm]") axes.set_ylabel("Scan Position [mm]") figure.savefig(img_file)
def my_draw(self): """ This function is used by DQL_visualization_actions.py to make video from sequence of actions """ fig = Figure() canvas = FigureCanvas(fig) ax = fig.gca() ax.imshow(self.image_playground) rect = patches.Rectangle((self.agent_window[0], self.agent_window[1]), self.agent_window[2] - self.agent_window[0], self.agent_window[3] - self.agent_window[1], linewidth=1, edgecolor='r', facecolor='none') ax.add_patch(rect) for target in [self.targets[0]]: rect2 = patches.Rectangle((target[0], target[1]), target[2] - target[0], target[3] - target[1], linewidth=1, edgecolor='b', facecolor='none') ax.add_patch(rect2) canvas.draw() width, height = fig.get_size_inches() * fig.get_dpi() return np.fromstring(canvas.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3)
def residuals_at_max_likelihood(mcmc_set): # Get the maximum likelihood parameters try: (max_likelihood, max_likelihood_position) = mcmc_set.maximum_likelihood() except NoPositionsException as npe: return Result(None, None) # Get the residuals residuals = mcmc_set.chains[0].get_residuals(max_likelihood_position) # Make the residuals plot fig = Figure() ax = fig.gca() plot_filename = '%s_max_likelihood_residuals.png' % mcmc_set.name thumbnail_filename = '%s_max_likelihood_residuals_th.png' % mcmc_set.name ax.plot(residuals[0], residuals[1]) ax.set_title('Residuals at Maximum Likelihood') #ax.xlabel('Time') #ax.ylabel('Residual') canvas = FigureCanvasAgg(fig) fig.set_canvas(canvas) fig.savefig(plot_filename) fig.savefig(thumbnail_filename, dpi=10) return ThumbnailResult(thumbnail_filename, plot_filename)
class SunPyPlot(FigureCanvas): """SunPy preview image""" def __init__(self, map_, width, height, parent=None, dpi=100, **matplot_args): #pylint: disable=W0613 #self._widthHint = width #self._heightHint = height self._origMap = map_ self._map = map_.resample((width, height)) # Old way (segfaults in some environements) #self.figure = self._map.plot_simple(**matplot_args) #FigureCanvas.__init__(self, self.figure) self.figure = Figure() self._map.plot(figure=self.figure, basic_plot=True, **matplot_args) self.axes = self.figure.gca() FigureCanvas.__init__(self, self.figure) # How can we get the canvas to preserve its aspect ratio when expanding? #sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) #sizePolicy.setHeightForWidth(True) #self.setSizePolicy(sizePolicy) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) self.setSizePolicy(sizePolicy) self.setMinimumSize(QtCore.QSize(width, height)) self.setMaximumSize(QtCore.QSize(width, height))
def plot_difference_histogram(group, gene_name, bins=np.arange(20.1)): """ Plot a histogram of percentage differences for a specific gene. """ exact_matches = group[group.V_SHM == 0] cdr3s_exact = len(set(s for s in exact_matches.CDR3_nt if s)) js_exact = len(set(exact_matches.J_gene)) fig = Figure(figsize=(100 / 25.4, 60 / 25.4)) ax = fig.gca() ax.set_xlabel('Percentage difference') ax.set_ylabel('Frequency') fig.suptitle('Gene ' + gene_name, y=1.08, fontsize=16) ax.set_title('{:,} sequences assigned'.format(len(group))) ax.text( 0.25, 0.95, '{:,} ({:.1%}) exact matches\n {} unique CDR3\n {} unique J'.format( len(exact_matches), len(exact_matches) / len(group), cdr3s_exact, js_exact), transform=ax.transAxes, fontsize=10, bbox=dict(boxstyle='round', facecolor='white', alpha=0.5), horizontalalignment='left', verticalalignment='top') _ = ax.hist(list(group.V_SHM), bins=bins) return fig
def plot_detection(self, image, result, labels): from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure figure = Figure() canvas = FigureCanvasAgg(figure) axes = figure.gca() colors = visualize.random_colors(len(labels)) visualize.display_instances(image, result['rois'], result['masks'], result['class_ids'], labels, result['scores'], ax=axes, colors=colors) figure.tight_layout() canvas.draw() r = np.fromstring(canvas.tostring_rgb(), dtype='uint8') x, y, w, h = figure.bbox.bounds r = r.reshape((int(h), int(w), 3)) return r
class PlotCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=144): self.fig = Figure(figsize=(width, height), dpi=dpi) self.axes = self.fig.add_subplot(111) self.fig.set_tight_layout(True) FigureCanvas.__init__(self, self.fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def create_toolbar(self, parent): return NavigationToolbar(self, parent) def plot(self, x_values, y_values, title, xlabel, linestyle, invert_y=True, *args, **kwargs): ax = self.fig.gca() # clear previous ax content, so replotting works ax.clear() # invert y axis (increase values downwards) if invert_y: ax.invert_yaxis() ax.plot(x_values, y_values, linestyle) ax.set_title(title) ax.set_xlabel(xlabel) ax.set_ylabel("Depth (m)") self.draw()
def screen_fig(): fig_ts = Figure(figsize=(x_size, y_size)) a = fig_ts.add_subplot(211) ax = fig_ts.gca() if int(matplotlib.__version__.split('.')[0]) == 2: ax.set_facecolor('black') else: ax.set_axis_bgcolor('black') a.plot(arg0, 'y') a.plot(0.5 * np.ones((len(arg0), )), 'w') a.plot(np.ones((len(arg0), )), 'm') a.plot(1.5 * np.ones((len(arg0), )), 'r') a.set_xlim(float(entries[0].get()), float(entries[1].get())) a.set_ylim(float(entries[2].get()), float(entries[3].get())) a.set_xlabel(entries[4].get()) a.set_ylabel(entries[5].get()) a.set_title(entries[6].get()) b = fig_ts.add_subplot(212) b.plot(arg1, arg2, 'b', label='$\mu$ = ' + arg4) b.plot(arg1, arg3, 'r', linewidth=2.0, label='$\sigma$ = ' + arg5) b.legend(loc=0) b.set_xlim(float(entries[7].get()), float(entries[8].get())) b.set_ylim(float(entries[9].get()), float(entries[10].get())) b.set_ylabel(entries[11].get()) b.set_xlabel(entries[12].get()) b.set_title(entries[13].get()) fig_ts.tight_layout() canvas = FigureCanvasTkAgg(fig_ts, master=frame_1) canvas.get_tk_widget().grid(row=0, column=0) canvas.draw()
def create_arrow_image(motion, pad=2): D = len(motion) assert D == 1, f"Only one direction right now. Currently, [{len(motion)}]" W = 100 S = (W + pad) * D + pad arrows = np.zeros((S, W + 2 * pad, 3)) direction = motion[0] for i in range(D): col_i = (pad + W) * i + pad canvas = arrows[col_i:col_i + W, pad:pad + W, :] start_point = (0, 0) x_end = direction[0].item() y_end = direction[1].item() end_point = (x_end, y_end) fig = Figure(dpi=300) plt_canvas = FigureCanvas(fig) ax = fig.gca() ax.annotate( "", xy=end_point, xycoords='data', xytext=start_point, textcoords='data', arrowprops=dict(arrowstyle="->", connectionstyle="arc3"), ) ax.set_xlim([-1, 1]) ax.set_ylim([-1, 1]) plt_canvas.draw() # draw the canvas, cache the renderer canvas = np.array(plt_canvas.buffer_rgba())[:, :, :] arrows = canvas arrows = torch.Tensor(arrows.astype(np.uint8)).transpose(0, 2).transpose( 1, 2) return arrows
def sample_fits(mcmc_set): tspan = mcmc_set.chains[0].options.tspan fig = Figure() ax = fig.gca() plot_filename = '%s_sample_fits.png' % mcmc_set.name thumbnail_filename = '%s_sample_fits_th.png' % mcmc_set.name # Make sure we can call the method 'get_observable_timecourses' if not hasattr(mcmc_set.chains[0], 'get_observable_timecourses') or \ not hasattr(mcmc_set.chains[0], 'plot_data'): return Result('None', None) # Plot the original data mcmc_set.chains[0].plot_data(ax) # Plot a sampling of trajectories from the original parameter set try: for i in range(num_samples): position = mcmc_set.get_sample_position() timecourses = mcmc_set.chains[0].get_observable_timecourses( position=position) for obs_name, timecourse in timecourses.iteritems(): ax.plot(tspan, timecourse, color='g', alpha=0.1, label=obs_name) except NoPositionsException as npe: pass canvas = FigureCanvasAgg(fig) fig.set_canvas(canvas) fig.savefig(plot_filename) fig.savefig(thumbnail_filename, dpi=10) return ThumbnailResult(thumbnail_filename, plot_filename)
def stroke_to_image(stroke, dpi, width_ratio=1, height_ratio=1): """Creates an image of a given stroke. The image size is determined by the dpi and given w&h ratios: height = dpi*height_ratio weight = dpi*width_ratio Args: stroke: numpy array of shape (# of points, 3) dpi: width_ratio: height_ratio: Returns: Image as numpy array of shape (width, height, 3). """ fig = Figure(figsize=(width_ratio, height_ratio), dpi=dpi) canvas = FigureCanvasAgg(fig) ax = fig.gca() ax.axis("off") ax.plot(stroke[:-1, 0], stroke[:-1, 1], lw=2, color="k") canvas.draw() width, height = width_ratio * dpi, height_ratio * dpi img = np.fromstring(canvas.tostring_rgb(), dtype="uint8") img = img.reshape(height, width, 3) return img
def initialize(self): fig = Figure(facecolor=(0.7490196,0.7490196,0.7490196,1), tight_layout=True) self.canvas = FigureCanvasWxAgg(self, -1, fig) self.canvas.SetExtraStyle(wx.EXPAND) self.ax = fig.gca(projection='3d', axisbg=(0.7490196,0.7490196,0.7490196,1)) self.Bind(wx.EVT_SIZE, self.onSize) self.Layout()
def plot_emcee_fits(gf, sampler, sample=True, burn=None, nsamples=100, plot_filename=None): """Plot fits from the MCMC chain vs. the data.""" if not DISPLAY and plot_filename is None: raise ValueError("DISPLAY is set to False but plot_filename is None, " "so there will be no output.") set_fig_params_for_publication() # If we're plotting samples, get the indices now and use them for # all observables if sample: (nwalkers, nsteps) = sampler.chain.shape[1:3] if burn is None: burn = int(nsteps / 2) walker_indices = np.random.randint(0, nwalkers, size=nsamples) step_indices = np.random.randint(burn, nsteps, size=nsamples) for obs_ix in range(gf.data.shape[1]): if DISPLAY: fig = plt.figure(figsize=(3, 3), dpi=300) else: fig = Figure(figsize=(3, 3), dpi=300) ax = fig.gca() ax.set_ylabel('$F/F_0$') #ax.set_xlabel(r'Time (sec $\times 10^3$)') ax.set_xlabel(r'Time') #plt.ylim([0.7, 5.2]) ax.set_xlim([0, gf.time[-1] + 500]) #ax.set_xticks(np.linspace(0, 1e4, 6)) #ax.set_xticklabels([int(f) for f in np.linspace(0, 10, 6)]) fig.subplots_adjust(bottom=0.21, left=0.20) # Plot the different observables for cond_ix in range(gf.data.shape[0]): data = gf.data[cond_ix, obs_ix, :] ax.plot(gf.time, data, 'k', linewidth=1) # Colors for different observables obs_colors = ['r', 'g', 'b', 'k'] # If we're plotting samples: if sample: for i in xrange(nsamples): p = sampler.chain[0, walker_indices[i], step_indices[i], :] plot_args = {'color': obs_colors[obs_ix], 'alpha': 0.1} gf.plot_func(p, obs_ix=obs_ix, ax=ax, plot_args=plot_args) # Plot the maximum a posteriori fit maxp_flat_ix = np.argmax(sampler.lnprobability[0]) maxp_ix = np.unravel_index(maxp_flat_ix, sampler.lnprobability[0].shape) maxp = sampler.lnprobability[0][maxp_ix] plot_args = {'color': 'm', 'alpha': 1} gf.plot_func(sampler.chain[0, maxp_ix[0], maxp_ix[1]], ax=ax, obs_ix=obs_ix, plot_args=plot_args) format_axis(ax) if plot_filename: obs_plot_filename = '%s.obs%d' % (plot_filename, obs_ix) save_fig(fig, obs_plot_filename, DISPLAY)
class MatplotlibWidget(FigureCanvas): def __init__(self, parent=None): super(MatplotlibWidget, self).__init__(Figure()) self.setParent(parent) self.figure = Figure() self.canvas = FigureCanvas(self.figure) self.axes = self.figure.gca()
def __init__( self, parent, grid, count, vmin=None, vmax=None, legend=None, codim=1, separate_plots=False, dpi=100 ): assert isinstance(grid, OnedGrid) assert codim in (0, 1) figure = Figure(dpi=dpi) if not separate_plots: axes = figure.gca() axes.hold(True) self.codim = codim lines = tuple() centers = grid.centers(1) if grid._identify_left_right: centers = np.concatenate((centers, [[grid._domain[1]]]), axis=0) self.periodic = True else: self.periodic = False if codim == 1: xs = centers else: xs = np.repeat(centers, 2)[1:-1] for i in xrange(count): if separate_plots: figure.add_subplot(int(count / 2) + count % 2, 2, i + 1) axes = figure.gca() pad = (vmax[i] - vmin[i]) * 0.1 axes.set_ylim(vmin[i] - pad, vmax[i] + pad) l, = axes.plot(xs, np.zeros_like(xs)) lines = lines + (l,) if legend and separate_plots: axes.legend([legend[i]]) if not separate_plots: pad = (max(vmax) - min(vmin)) * 0.1 axes.set_ylim(min(vmin) - pad, max(vmax) + pad) if legend: axes.legend(legend) self.lines = lines super(Matplotlib1DWidget, self).__init__(figure) self.setParent(parent) self.setMinimumSize(300, 300) self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
def viewCompartmentGeo(G): # creates pop up window compartmentgeo = Toplevel(bg='gray', highlightbackground='gray') compartmentgeo.title("Compartment Geometry") var = IntVar() checkbox = Checkbutton(compartmentgeo, bg='gray', highlightbackground='gray', text='show intersection lines', variable=var) checkbox.pack() fig = Figure() canvas = FigureCanvasTkAgg(fig, master=compartmentgeo) checkbox.config(command= lambda: compartmentDisplay(var, canvas, compartmentgeo, G, checkbox)) ax = fig.gca(projection='3d') ax.set_aspect("equal") voxelHandler = vox.voxelHandler(1) # loops through every node with type: compartment, and graphs cubes with given centroid and edge length for node in G.nodes(): if 'Type' in G.node[node]: if G.node[node]['Type'] == 'Compartment': #loop through each sub geometry and plot the cube with centroid x,y,z and edge length a cubePos = [] for i in range(0, len(G.node[node]['x'])): a = G.node[node]['EdgeLength'][i] x = G.node[node]['x'][i] y = G.node[node]['y'][i] z = G.node[node]['z'][i] hSL = float(a/2) x1 = x-hSL #int(x - hSL) x2 = x+hSL #int(x + hSL) y1 = y-hSL #int(y - hSL) y2 = y+hSL #int(y + hSL) z1 = z-hSL #int(z - hSL) z2 = z+hSL #int(z + hSL) curBox = voxelHandler.custBox(x1, x2, y1, y2, z1, z2) cubePos.append(curBox) compList = voxelHandler.listAppend(cubePos) curChunk = voxelHandler.createChunk(compList) voxelHandler.createOutline(curChunk) voxelHandler.drawCubeLines(curChunk,ax) # sets the scales of the graph to be equal so that cube shape is intact scaling = np.array([getattr(ax, 'get_{}lim'.format(dim))() for dim in 'xyz']) ax.auto_scale_xyz(*[[np.min(scaling), np.max(scaling)]]*3) # creates matplotlib navigation toolbar canvas.show() canvas.get_tk_widget().configure(borderwidth=0, highlightbackground='gray', highlightcolor='gray', selectbackground='gray') canvas.get_tk_widget().pack() toolbar = NavigationToolbar2TkAgg(canvas, compartmentgeo) toolbar.update()
def get(self): uid, figid = 'deadbeef', '1' self.application.prog_states[uid] = None fig = Figure(frameon=False, tight_layout=True) ax = fig.gca() for k, traj in SPECTRA.iteritems(): ax.plot(*traj.T, label=k) ax.legend() RC_LINE.extend(ax.plot(traj[:,0], traj[:,1]*0, 'k--')) self.application.fig_managers[figid] = make_fig_manager(figid, fig) self.write(demo_tpl.generate(uid=uid, figid=figid, host=self.request.host))
def test_plot_topomap_interactive(): """Test interactive topomap projection plotting.""" import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure evoked = read_evokeds(evoked_fname, baseline=(None, 0))[0] evoked.pick_types(meg='mag') evoked.info['projs'] = [] assert not evoked.proj evoked.add_proj(compute_proj_evoked(evoked, n_mag=1)) plt.close('all') fig = Figure() canvas = FigureCanvas(fig) ax = fig.gca() kwargs = dict(vmin=-240, vmax=240, times=[0.1], colorbar=False, axes=ax, res=8, time_unit='s') evoked.copy().plot_topomap(proj=False, **kwargs) canvas.draw() image_noproj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8') assert len(plt.get_fignums()) == 1 ax.clear() evoked.copy().plot_topomap(proj=True, **kwargs) canvas.draw() image_proj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8') assert not np.array_equal(image_noproj, image_proj) assert len(plt.get_fignums()) == 1 ax.clear() evoked.copy().plot_topomap(proj='interactive', **kwargs) canvas.draw() image_interactive = np.frombuffer(canvas.tostring_rgb(), dtype='uint8') assert_array_equal(image_noproj, image_interactive) assert not np.array_equal(image_proj, image_interactive) assert len(plt.get_fignums()) == 2 proj_fig = plt.figure(plt.get_fignums()[-1]) _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data') canvas.draw() image_interactive_click = np.frombuffer( canvas.tostring_rgb(), dtype='uint8') assert_array_equal(image_proj, image_interactive_click) assert not np.array_equal(image_noproj, image_interactive_click) _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data') canvas.draw() image_interactive_click = np.frombuffer( canvas.tostring_rgb(), dtype='uint8') assert_array_equal(image_noproj, image_interactive_click) assert not np.array_equal(image_proj, image_interactive_click)
def __init__(self, master, item, event): tk.Toplevel.__init__(self, master) self.wm_title("Waveform: event #{}".format(item)) fig = Figure(figsize=(4,3), dpi=100) canvas = FigureCanvasTkAgg(fig, self) canvas.get_tk_widget().pack(fill=tk.BOTH, expand=1) toolbar = NavigationToolbar2TkAgg(canvas, self) ax = fig.gca() event.plot(ax) ax.set_title("Event #{}".format(item)) ax.grid(True) fig.tight_layout() self.update()
def legend_categorical(target_dir): # this just generates pieces, still need to manually assemble them # into the final result f = Figure(figsize=(300/dpi, 300/dpi), dpi=dpi) ax = f.gca() for subtype, shape in (('HER2amp', 'triangle'), ('TN', 'circle'), ('HR+', 'square')): ax.plot(0, 0, marker=marker_map[shape].marker, mfc=marker_map[shape].color, label=subtype, ls='none') ax.legend(prop={'size': 12}) filename = op.join(target_dir, 'legend-categorical.png') canvas = FigureCanvasAgg(f) canvas.print_png(filename)
class MplCanvas(FigureCanvas): """Class to represent the FigureCanvas widget""" def __init__(self): # setup Matplotlib Figure and Axis self.fig = Figure() self.ax = self.fig.gca() self.ax = self.fig.add_subplot(111) # initialization of the canvas FigureCanvas.__init__(self, self.fig) # we define the widget as expandable FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) # notify the system of updated policy FigureCanvas.updateGeometry(self)
def __init__(self, parent, grid, count, vmin=None, vmax=None, legend=None, codim=1, separate_plots=False, dpi=100): assert grid.reference_element is line assert codim in (0, 1) figure = Figure(dpi=dpi) if not separate_plots: axes = figure.gca() axes.hold(True) self.codim = codim lines = tuple() if codim == 1: xs = grid.centers(1) else: xs = np.repeat(grid.centers(1), 2)[1:-1] for i in xrange(count): if separate_plots: figure.add_subplot(int(count / 2) + count % 2, 2, i + 1) axes = figure.gca() pad = (vmax[i] - vmin[i]) * 0.1 axes.set_ylim(vmin[i] - pad, vmax[i] + pad) l, = axes.plot(xs, np.zeros_like(xs)) lines = lines + (l,) if legend and separate_plots: axes.legend([legend[i]]) if not separate_plots: pad = (max(vmax) - min(vmin)) * 0.1 axes.set_ylim(min(vmin) - pad, max(vmax) + pad) if legend: axes.legend(legend) self.lines = lines super(Matplotlib1DWidget, self).__init__(figure) self.setParent(parent) self.setMinimumSize(300, 300) self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
def generate_sample_plot(self, output_filename, width=5, height=5, title="Sample Data"): """Generates a sample plot of random data""" # Initialize matplotlib plot formatting to sane defaults mainmodel.init_matplotlib_defaults() figure = Figure(figsize=(width, height)) canvas = FigureCanvas(figure) axes = figure.gca() x = np.arange(-10, 10) data = np.sinc(x + random.uniform(-.25, .25)) linestyles = ['_', '-', '--', ':'] colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k') axes.plot(x, data, linestyle=random.choice(linestyles), marker=".", color=random.choice(colors)) axes.set_title(title) axes.grid(True) figure.savefig(output_filename, format='png')
class HistogramSelector(Gtk.Dialog): __gtype_name__ = 'SASGUI_HistogramSelector' def __init__(self, data, *args, **kwargs): Gtk.Dialog.__init__(self, *args, **kwargs) self.set_default_response(Gtk.ResponseType.CANCEL) self._data = data vbox = self.get_content_area() hbox = Gtk.HBox() vbox.pack_start(hbox, False, True, 0) l = Gtk.Label(label='Number of histogram bins:') l.set_alignment(0, 0.5) hbox.pack_start(l, False, True, 0) self.nbins_spin = Gtk.SpinButton() hbox.pack_start(self.nbins_spin, True, True, 0) self.nbins_spin.set_range(1, 1e100) self.nbins_spin.set_increments(1, 10) self.nbins_spin.set_digits(0) self.nbins_spin.set_numeric(True) # self.nbins_spin.connect('changed', self.on_nbins_changed) b = Gtk.Button(stock=Gtk.STOCK_APPLY) hbox.pack_start(b, False, True, 0) b.connect('clicked', self.on_nbins_changed) self.fig = Figure((640 / 72., 480 / 72.), 72) self.canvas = FigureCanvasGTK3Agg(self.fig) self.canvas.set_size_request(300, 200) vbox.pack_start(self.canvas, True, True, 0) self.figure_toolbar = NavigationToolbar2GTK3(self.canvas, self) vbox.pack_start(self.figure_toolbar, False, True, 0) self.fig.add_subplot(1, 1, 1) self.show_all() self.hide() def get_data(self): return self._data def set_data(self, value): self._data = value self.on_bins_changed(None) data = property(get_data, set_data) def set_nbins(self, value): self.nbins_spin.set_value(value) self.on_nbins_changed(self.nbins_spin) def get_nbins(self): return self.nbins_spin.get_value_as_int() nbins = property(get_nbins, set_nbins) def redraw(self): self.fig.gca().cla() self.fig.gca().hist(self.data.flatten(), self.nbins) self.fig.canvas.draw() return False def on_nbins_changed(self, widget): GObject.idle_add(self.redraw) return True def get_xlimits(self): return self.fig.gca().axis()[0:2] def gca(self): return self.fig.gca()
def create_plot(data, title, width, height): """Generates a matplotlib Figure instance of the specified data""" mainmodel.init_matplotlib_defaults() figure = Figure(figsize=(width, height)) canvas = FigureCanvas(figure) axes = figure.gca() if 2 in data.shape: axes.plot(data[0], data[1]) elif data.ndim == 1: axes.plot(data) else: img = axes.imshow(data, cmap=cm.get_cmap('Spectral')) figure.colorbar(img) if len(title) > 20: title = ''.join([title[:10], "...", title[-10:]]) axes.set_title(title) axes.grid(True) return figure
def increase_Bax_5x(mcmc_set): """ .. todo:: document the basis for this""" tspan = mcmc_set.chains[0].options.tspan fig = Figure() ax = fig.gca() plot_filename = '%s_Bax_5x.png' % mcmc_set.name thumbnail_filename = '%s_Bax_5x_th.png' % mcmc_set.name # Make sure we can call the method 'get_observable_timecourses' if not hasattr(mcmc_set.chains[0], 'get_observable_timecourses') or \ not hasattr(mcmc_set.chains[0], 'plot_data'): return Result('None', None) # Plot the original data mcmc_set.chains[0].plot_data(ax) # Plot a sampling of trajectories from the original parameter set for i in range(num_samples): position = mcmc_set.get_sample_position() timecourses = mcmc_set.chains[0].get_observable_timecourses(position=position) for obs_name, timecourse in timecourses.iteritems(): ax.plot(tspan, timecourse, color='g', alpha=0.5, label=obs_name) # Now increase Bax 5-fold... model = mcmc_set.chains[0].options.model old_Bax_0 = model.parameters['Bax_0'].value model.parameters['Bax_0'].value = old_Bax_0 * 5 # ...and do the sampling again for i in range(num_samples): position = mcmc_set.get_sample_position() timecourses = mcmc_set.chains[0].get_observable_timecourses(position=position) for obs_name, timecourse in timecourses.iteritems(): ax.plot(tspan, timecourse, color='r', alpha=0.5, label=obs_name) canvas = FigureCanvasAgg(fig) fig.set_canvas(canvas) fig.savefig(plot_filename) fig.savefig(thumbnail_filename, dpi=10) # Make sure to reset the Bax initial condition to its original value! model.parameters['Bax_0'].value = old_Bax_0 return ThumbnailResult(thumbnail_filename, plot_filename)
def fit_plotting_function(self, position): """Gets the observable timecourse and plots it against the data. Useful for visualizing model output by examining the fit of the model at the maximum likelihood or maximum a posteriori parameters, etc. Parameters ---------- position : numpy.array Vector of parameter values to use for simulation and plotting. Returns ------- matplotlib.figure.Figure Figure instance containing the plot of the data and the simulation at the given position. """ # Run the simulation at the given position timecourses = self.get_observable_timecourses(position) # Make the plot fig = Figure() ax = fig.gca() # Add the data to the plot self.plot_data(ax) # Add the simulations to the plot for obs_name, timecourse in timecourses.iteritems(): ax.plot(timecourse[0], timecourse[1], label=obs_name) # Label the plot ax.set_xlabel('Time') ax.set_ylabel('Concentration') fontP = FontProperties() fontP.set_size('small') box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) ax.legend(loc='upper left', prop=fontP, ncol=1, bbox_to_anchor=(1, 1), fancybox=True, shadow=True) #ax.legend(loc='upper center', prop=fontP, ncol=5, # bbox_to_anchor=(0.5, 1.1), fancybox=True, shadow=True) canvas = FigureCanvasAgg(fig) fig.set_canvas(canvas) return fig
def iBax_monotonically_increasing(mcmc_set): """ .. todo:: document the basis for this""" tspan = mcmc_set.chains[0].options.tspan fig = Figure() ax = fig.gca() plot_filename = '%s_iBax_monotonic_increasing.png' % mcmc_set.name num_true = 0 for i in range(num_samples): x = mcmc_set.get_sample_simulation() ax.plot(tspan, x['iBax'], color='r', alpha=0.5) if monotonic_increasing(x['iBax']): num_true += 1 canvas = FigureCanvasAgg(fig) fig.set_canvas(canvas) fig.savefig(plot_filename) return FuzzyBooleanResult(float(num_true) / float(num_samples), plot_filename, expectation=1.0)
def _config_canvas(self): """Load the MatPlotLib drawing code""" # Create the drawing canvas figure = Figure(figsize=(6,6), dpi=100) self._canvas = FigureCanvasTkAgg(figure, master=self._root) self._canvas._tkcanvas.pack(side=Tk.LEFT, expand=True, fill=Tk.BOTH) # Initialize the scatter plot self._axes = figure.gca(projection='3d') self._axes.set_xlim((0.0, 1.0)) self._axes.set_ylim((0.0, 1.0)) self._axes.set_zlim((0.0, 1.0)) self._axes.set_xlabel('X') self._axes.set_ylabel('Y') self._axes.set_zlabel('Z') self._axes.set_xticks(numpy.arange(0.0,1.0,0.1)) self._axes.set_yticks(numpy.arange(0.0,1.0,0.1)) self._axes.set_zticks(numpy.arange(0.0,1.0,0.1)) self._axes.tick_params(labelsize=9)