def segmented_image(arr): """Get segmented image as a numpy array""" colors_dic = {'0':'#ffd300', '1':'#93cc93', '2':'#4970a3', '3':'#999999'} keys = list(np.unique(arr)) keys = [str(i) for i in keys] colors = [colors_dic.get(key) for key in keys] cmap = mpl.colors.ListedColormap(colors) fig = Figure() fig.set_size_inches(256/fig.get_dpi(), 256/fig.get_dpi()) fig.subplots_adjust(0,0,1,1) canvas = FigureCanvas(fig) ax = fig.gca() plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0) ax.imshow(arr, cmap=cmap) ax.axis('off') ax.margins(0,0) canvas.draw() # draw the canvas, cache the renderer 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
def canvas(self): type = self.get("imageType", "png") fig = Figure() if type == "png": canvas = FigureCanvasAgg(fig) (self.file, self.filename) = mkstemp(".%s" % type) elif type == "svg": canvas = FigureCanvasSVG(fig) (self.file, self.filename) = mkstemp(".%s" % type) elif type == "pdf": canvas = FigureCanvasPdf(fig) (self.file, self.filename) = mkstemp(".%s" % type) elif type == "ps" or type == "eps": canvas = FigureCanvasPS(fig) (self.file, self.filename) = mkstemp(".%s" % type) else: raise "Invalid render target requested" # Set basic figure parameters dpi = float(self.get('dpi')) (w, h) = (float(self.get('width')), float(self.get('height'))) (win, hin) = (w/dpi, h/dpi) fig.set_size_inches(win, hin) fig.set_dpi(dpi) fig.set_facecolor('white') return (fig, canvas, w, h)
def plot_log_well_path(request, object_id) : run = Run.objects.get(pk=object_id) data = ToolMWDLog.objects.filter(run=run).order_by('depth') north = [0,] east = [0,] vert = [0,] for c in range(len(data)-1) : dv, dn, de = min_curve_delta(data[c].depth,data[c].inclination,data[c].azimuth, data[c+1].depth, data[c+1].inclination, data[c+1].azimuth) north.append(dn + north[c]) east.append(de + east[c]) vert.append(dv + vert[c]) fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_axes([0.15, 0.1, 0.8, 0.8]) ax.grid(True) ax.plot(east, north) ax.set_title('Well Plot') ax.set_ylabel('North') ax.set_xlabel('East') fig.set_size_inches( (5, 5) ) filename = settings.MEDIA_ROOT + '/images/wellplot.png' fig.savefig(filename) return HttpResponseRedirect('/tdsurface/media/images/wellplot.png')
class wxMatplotPanelSimple( wx.Panel ): def __init__( self, renderPanel, color=None, dpi=None, **kwargs ): from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.figure import Figure # initialize Panel if 'id' not in list(kwargs.keys()): kwargs['id'] = wx.ID_ANY if 'style' not in list(kwargs.keys()): kwargs['style'] = wx.NO_FULL_REPAINT_ON_RESIZE wx.Panel.__init__( self, renderPanel, **kwargs ) self.figure = Figure( None, dpi ) #self.canvas = NoRepaintCanvas( self, -1, self.figure ) self.canvas = FigureCanvasWxAgg( self, -1, self.figure ) sizer = wx.BoxSizer(); sizer.Add( self.canvas, 1, wx.EXPAND ) self.SetSizer( sizer ) self.axes = self.figure.add_subplot( 111 ) self.axes.set_aspect( 'auto' ) self.Bind(wx.EVT_SIZE, self._onSize) def _onSize( self, event = None ): pixels = tuple( [ self.GetSize()[0], self.GetSize()[1] ] ) print(pixels) #if self.canvas.GetMinSize( )[0] != pixels[0] or \ #self.canvas.GetMinSize( )[1] != pixels[1] : self.canvas.SetMinSize( pixels ) self.figure.set_size_inches( float( pixels[ 0 ] )/self.figure.get_dpi(), float( pixels[ 1 ] )/self.figure.get_dpi() ) self.canvas.draw()
class PlotPanel(wx.Panel): """ The PlotPanel has a Figure and a Canvas. OnSize events simply set a flag, and the actual resizing of the figure is triggered by an Idle event. """ def __init__(self, parent, obj_id): # initialize Panel wx.Panel.__init__(self, parent, obj_id) # initialize matplotlib stuff self.figure = Figure(None, None) self.canvas = FigureCanvasWxAgg(self, wx.ID_ANY, self.figure) rgbtuple = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE).Get() clr = [c / 255. for c in rgbtuple] self.figure.set_facecolor(clr) self.figure.set_edgecolor(clr) self.canvas.SetBackgroundColour(wx.Colour(*rgbtuple)) self.Bind(wx.EVT_SIZE, self._on_size) def _on_size(self, event): self._set_size() def _set_size(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 draw(self): pass # abstract, to be overridden by child classes
def changeFigureSize(w: float, h: float, cut_from_top: bool = False, cut_from_left: bool = False, fig: Figure = None): """ change the figure size to the given dimensions. Optionally define if to remove or add space at the top or bottom and left or right. """ if fig is None: fig = plt.gcf() oldw, oldh = fig.get_size_inches() fx = oldw / w fy = oldh / h for axe in fig.axes: box = axe.get_position() if cut_from_top: if cut_from_left: axe.set_position([1 - (1 - box.x0) * fx, box.y0 * fy, (box.x1 - box.x0) * fx, (box.y1 - box.y0) * fy]) else: axe.set_position([box.x0 * fx, box.y0 * fy, (box.x1 - box.x0) * fx, (box.y1 - box.y0) * fy]) else: if cut_from_left: axe.set_position( [1 - (1 - box.x0) * fx, 1 - (1 - box.y0) * fy, (box.x1 - box.x0) * fx, (box.y1 - box.y0) * fy]) else: axe.set_position([box.x0 * fx, 1 - (1 - box.y0) * fy, (box.x1 - box.x0) * fx, (box.y1 - box.y0) * fy]) for text in fig.texts: x0, y0 = text.get_position() if cut_from_top: if cut_from_left: text.set_position([1 - (1- x0) * fx, y0 * fy]) else: text.set_position([x0 * fx, y0 * fy]) else: if cut_from_left: text.set_position([1 - (1 - x0) * fx, 1 - (1 - y0) * fy]) else: text.set_position([x0 * fx, 1 - (1 - y0) * fy]) fig.set_size_inches(w, h, forward=True)
def matplotlib_figure(width, height): """Create a Matplotlib figure with specified width and height for rendering. w Width of desired plot. h Height of desired plot. return A Matplotlib figure. """ try: from matplotlib.backends.backend_agg import FigureCanvasAgg except: paraview.print_error("Error: Cannot import matplotlib.backends.backend_agg.FigureCanvasAgg") try: from matplotlib.figure import Figure except: paraview.print_error("Error: Cannot import matplotlib.figure.Figure") figure = Figure() figureCanvas = FigureCanvasAgg(figure) figure.set_dpi(72) figure.set_size_inches(float(width)/72.0, float(height)/72.0) return figure
class wxMatplotPanelSimple(wx.Panel): def __init__(self, renderPanel, color=None, dpi=None, **kwargs): from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.figure import Figure # initialize Panel if 'id' not in list(kwargs.keys()): kwargs['id'] = wx.ID_ANY if 'style' not in list(kwargs.keys()): kwargs['style'] = wx.NO_FULL_REPAINT_ON_RESIZE wx.Panel.__init__(self, renderPanel, **kwargs) self.figure = Figure(None, dpi) #self.canvas = NoRepaintCanvas( self, -1, self.figure ) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) sizer = wx.BoxSizer() sizer.Add(self.canvas, 1, wx.EXPAND) self.SetSizer(sizer) self.axes = self.figure.add_subplot(111) self.axes.set_aspect('auto') self.Bind(wx.EVT_SIZE, self._onSize) def _onSize(self, event=None): pixels = tuple([self.GetSize()[0], self.GetSize()[1]]) print(pixels) # if self.canvas.GetMinSize( )[0] != pixels[0] or \ # self.canvas.GetMinSize( )[1] != pixels[1] : self.canvas.SetMinSize(pixels) self.figure.set_size_inches( float(pixels[0]) / self.figure.get_dpi(), float(pixels[1]) / self.figure.get_dpi()) self.canvas.draw()
def print_image(x, y, x2, y2, outfile_name): fig = Figure(linewidth=0.0) fig.set_size_inches(fig_width, fig_length, forward=True) Figure.subplots_adjust(fig, left=fig_left, right=fig_right, bottom=fig_bottom, top=fig_top, hspace=fig_hspace) _subplot = fig.add_subplot(2, 1, 1) _subplot.set_title('Detection of Source generating non-wifi Interference') _subplot.plot(x, y, color='b') _subplot.set_xlabel('Time') _subplot.set_ylabel('Error Counts') # _subplot.set_ylim([0,1]) _subplot2 = fig.add_subplot(2, 1, 2) _subplot2.plot(x2, y2, color='r') # plotting the spectrum _subplot2.set_ylabel('Entropy') _subplot2.set_xlabel('Time') _subplot2.set_ylim([0, 1]) canvas = FigureCanvasAgg(fig) if '.eps' in outfile_name: canvas.print_eps(outfile_name, dpi=110) if '.png' in outfile_name: canvas.print_figure(outfile_name, dpi=110)
class PlotPanel(wx.Panel): """The PlotPanel has a Figure and a Canvas. OnSize events simply set a flag, and the actual resizing of the figure is triggered by an Idle event.""" def __init__(self, parent, color=None, dpi=None, **kwargs): from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.figure import Figure self.parent = parent # initialize Panel if 'id' not in kwargs.keys(): kwargs['id'] = wx.ID_ANY if 'style' not in kwargs.keys(): kwargs['style'] = wx.NO_FULL_REPAINT_ON_RESIZE wx.Panel.__init__(self, parent, **kwargs) # initialize matplotlib stuff self.figure = Figure(None, dpi) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.SetColor(color) self._SetSize() self.initial_draw() self._resizeflag = False self._redrawflag = False self.Bind(wx.EVT_IDLE, self._onIdle) self.Bind(wx.EVT_SIZE, self._onSize) def SetColor(self, rgbtuple=None): """Set figure and canvas colours to be the same.""" if rgbtuple is None: rgbtuple = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE).Get() clr = [c/255. for c in rgbtuple] self.figure.set_facecolor(clr) self.figure.set_edgecolor(clr) self.canvas.SetBackgroundColour(wx.Colour(*rgbtuple)) def _onSize(self, event): self._resizeflag = True def _onIdle(self, evt): with draw_lock: if self._resizeflag: self._resizeflag = False self._SetSize() if self._redrawflag: self._redrawflag = False self.canvas.draw() def _SetSize(self): # When drawing from another thread, I think this may need a lock pixels = tuple(self.parent.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 initial_draw(self): pass # abstract, to be overridden by child classes
class SimpleFigure(FigureCanvas): def __init__(self, parent=None, subplot=111, width=8, height=6, dpi=100): self.fig = Figure(figsize=(width, height), dpi=dpi) self.fig.patch.set_facecolor("None") self.axes = self.fig.add_subplot(subplot) FigureCanvas.__init__(self, self.fig) self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.setStyleSheet("background-color:transparent;") self.updateGeometry() def save(self, name="figure.png"): self.axes.xaxis.label.set_color('black') self.axes.yaxis.label.set_color('black') self.axes.title.set_color('black') self.axes.tick_params(axis='x', colors='black') self.axes.tick_params(axis='y', colors='black') self.fig.set_size_inches(7, 5) self.fig.savefig(name, format='png', dpi=300) self.axes.xaxis.label.set_color('white') self.axes.yaxis.label.set_color('white') self.axes.title.set_color('white') self.axes.tick_params(axis='x', colors='white') self.axes.tick_params(axis='y', colors='white')
def template_plotter(x_axis_label, y_axis_label,x_axes=[],x_ticks=[],title, outfile_name): fig = Figure(linewidth=0.0) fig.set_size_inches(fig_width,fig_length, forward=True) Figure.subplots_adjust(fig, left = fig_left, right = fig_right, bottom = fig_bottom, top = fig_top, hspace = fig_hspace) _subplot = fig.add_subplot(1,1,1) _subplot.boxplot(x_axis,notch=0,sym='+',vert=1, whis=1.5) #_subplot.plot(x,y,color='b', linestyle='--', marker='o' ,label='labels') a =[i for i in range(1,len(x_ticks)+1)] _subplot.set_xticklabels(x_ticks) _subplot.set_xticks(a) labels=_subplot.get_xticklabels() for label in labels: label.set_rotation(30) _subplot.set_ylabel(y_axis_label,fontsize=36) _subplot.set_xlabel(x_axis_label) #_subplot.set_ylim() #_subplot.set_xlim() _subplot.set_title(title) _subplot.legend(loc='upper left',prop=LEGEND_PROP ,bbox_to_anchor=(0.5, -0.05)) canvas = FigureCanvasAgg(fig) if '.eps' in outfile_name: canvas.print_eps(outfile_name, dpi = 110) if '.png' in outfile_name: canvas.print_figure(outfile_name, dpi = 110) outfile_name='EpsilonvsMTU.pdf' if '.pdf' in outfile_name: canvas.print_figure(outfile_name, dpi = 110)
class PlotPanel(XmlPanel): """Draw a plot (graph)""" def __init__(self, parent,elem): XmlPanel.__init__(self, parent) self.border = True self.elem = elem self.figure = Figure() self.applySize() self.plot = FigureCanvas(self,-1,self.figure) # FancyText(self,"hi") self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.plot, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.sizer) self.Fit() self.render() def applySize(self): size = self.elem.attrib.get("size",None) if size: psize = self.parent.GetSize() try: size = literal_eval(size) size = (min(psize[0],size[0]), min(psize[1],size[1])) # graph can't be bigger than the xmlterm self.SetInitialSize(size) self.SetSize(size) dpi = self.figure.get_dpi() self.figure.set_size_inches(float(size[0])/dpi,float(size[1])/dpi) # self.plot.SetSize(size) self.Fit() except ValueError,e: # size is malformed print "bad size" pass return size return None
def __init__(self, figure=None, logger=None, width=500, height=500): Callback.Callbacks.__init__(self) if figure is None: figure = Figure() dpi = figure.get_dpi() if dpi is None or dpi < 0.1: dpi = 100 wd_in, ht_in = float(width)/dpi, float(height)/dpi figure.set_size_inches(wd_in, ht_in) self.fig = figure if hasattr(self.fig, 'set_tight_layout'): self.fig.set_tight_layout(True) self.logger = logger self.fontsize = 10 self.ax = None self.logx = False self.logy = False self.xdata = [] self.ydata = [] # For callbacks for name in ('draw-canvas', ): self.enable_callback(name)
class PlotPanel(wx.Panel): """ The PlotPanel has a Figure and a Canvas. OnSize events simply set a flag, and the actual resizing of the figure is triggered by an Idle event. """ def __init__(self, parent, obj_id): # initialize Panel wx.Panel.__init__(self, parent, obj_id) # initialize matplotlib stuff self.figure = Figure(None, None) self.canvas = FigureCanvasWxAgg(self, wx.ID_ANY, self.figure) rgbtuple = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE).Get() clr = [c / 255.0 for c in rgbtuple] self.figure.set_facecolor(clr) self.figure.set_edgecolor(clr) self.canvas.SetBackgroundColour(wx.Colour(*rgbtuple)) self.Bind(wx.EVT_SIZE, self._on_size) def _on_size(self, event): self._set_size() def _set_size(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 draw(self): pass # abstract, to be overridden by child classes
class MathTextLabel(QWidget): def __init__(self, mathText, size, parent=None, **kwargs): QWidget.__init__(self, parent, **kwargs) l = QVBoxLayout(self) l.setContentsMargins(0, 0, 0, 0) r, g, b, a = self.palette().base().color().getRgbF() self._figure = Figure(edgecolor=(r, g, b), facecolor=(r, g, b)) self._canvas = FigureCanvas(self._figure) l.addWidget(self._canvas) self._figure.clear() text = self._figure.suptitle(mathText, x=0.0, y=1.0, horizontalalignment='left', verticalalignment='top', size=size) self._canvas.draw() (x0, y0), (x1, y1) = text.get_window_extent().get_points() w = x1 - x0 h = y1 - y0 self._figure.set_size_inches(w / 80, h / 80) self.setFixedSize(w, h)
def plot_image(group): q = select([log_t.c.query_time, log_t.c.amount_in_queue], log_t.c.id == group_t.c.id) q = q.where(group_t.c.group_name == group) q = q.where(log_t.c.query_time >= datetime.now() - timedelta(hours=4)) q = q.order_by(log_t.c.query_time) thresh = Group.query.filter_by(group_name=group).first().surplus_threshold data = list(q.execute()) if len(data) < 1: return redirect(url_for("main_menu")) png_data = StringIO() # Zip() with a '*' is a projection, who knew? time, count = zip(*data) fig = Figure() fig.set_size_inches(11, 8.5) axis = fig.add_subplot(1, 1, 1) axis.plot(time, count, marker=".") axis.xaxis.set_major_formatter(DateFormatter("%m/%d %H:%M")) fig.autofmt_xdate() axis.axhline(thresh, color="red", linestyle="-.") canvas = FigureCanvas(fig) canvas.print_png(png_data) response = make_response(png_data.getvalue()) response.mimetype = "image/png" return response
def plot_player_heroes(data: DataFrame, fig: Figure): fig.set_size_inches(6, 10) axes = fig.subplots(5) def _plot_player(column: Series, name: str, axis, colour: str): # This filters out zeroes in a series # column = column.iloc[column.nonzero()] column = column.iloc[column.to_numpy().nonzero()] if column.empty: axis.text(0.5, 0.5, "No Data", fontsize=14, horizontalalignment='center', verticalalignment='center') axis.set_ylabel(name) axis.yaxis.set_major_locator(MaxNLocator(integer=True)) return axis, [] column.sort_values(ascending=False, inplace=True) ax: Axes = column.plot.bar(ax=axis, sharey=True, colormap=colour) ax.set_ylabel(name) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) extra_artists = x_label_icon(ax, y_pos=-0.2, size=0.8) return ax, extra_artists extra_artists = [] for i_ax, player in enumerate(data.columns): ax, extra = _plot_player(data[player], player, axes[i_ax], colour=colour_list[i_ax]) extra_artists += extra return fig, extra_artists
def plot_WT_EDTA(df_WT, WT_label, xlabel, ylabel, xlim_max, ylim_max, fig_title, legend_title, legend_position, fig_height, fig_width_multiplier): print df_WT fig = Figure() # A canvas must be manually attached to the figure (pyplot would automatically # do it). This is done by instantiating the canvas with the figure as # argument. FigureCanvas(fig) ax = fig.add_subplot(111) ax.plot([1, 2, 3]) x = df_WT["timedelta"] y = df_WT["well_mean"] yerr = df_WT["well_std"] WT_line = ax.errorbar(x, y, yerr, fmt=WT_format, markersize=default_marker_size) WT_line.set_label(WT_label) ax.legend(loc=legend_position, title=legend_title) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.set_xlim(-1 * 1, xlim_max) ax.set_ylim(-1 * 0.001, ylim_max) ax.annotate("EDTA", xy=(600, 0.02), xycoords='data', xytext=(300, 0.0222), textcoords='data', arrowprops=dict(arrowstyle="->", connectionstyle="arc3"), ) ax.set_title(fig_title) fig.set_size_inches(fig_height * fig_width_multiplier, fig_height) fig.tight_layout(pad=0.4) return fig
def plot_vs_WT(df_WT, df_mutant, mutant_label, xlabel, ylabel, xlim_max, ylim_max, fig_title, legend_title, legend_position, fig_height, fig_width_multiplier): print df_WT fig = Figure() # A canvas must be manually attached to the figure (pyplot would automatically # do it). This is done by instantiating the canvas with the figure as # argument. FigureCanvas(fig) ax = fig.add_subplot(111) ax.plot([1, 2, 3]) x = df_WT["timedelta"] y = df_WT["well_mean"] yerr = df_WT["well_std"] WT_line = ax.errorbar(x, y, yerr, fmt=WT_format, markersize=default_marker_size) WT_line.set_label("WT") x = df_mutant["timedelta"] y = df_mutant["well_mean"] yerr = df_mutant["well_std"] mutant_line = ax.errorbar(x, y, yerr, fmt=variant1_format, markersize=default_marker_size) mutant_line.set_label(mutant_label) ax.legend(loc=legend_position, title=legend_title) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.set_xlim(0, xlim_max) ax.set_ylim(0, ylim_max) ax.set_title(fig_title) fig.set_size_inches(fig_height * fig_width_multiplier, fig_height) fig.tight_layout(pad=0.4) return fig
def __init__(self, window): self.window = window self.star = genstar.gen_star() self.use_lines = BooleanVar(window, True) self.use_points = BooleanVar(window, False) fig = Figure() fig.set_size_inches(6, h=2, forward=True) self.plot = fig.add_subplot(1, 1, 1) self.plot.set_title("Star Luminance", fontsize=16) self.plot.set_ylabel("%", fontsize=14) self.plot.set_xlabel("day", fontsize=14) self.canvas = FigureCanvasTkAgg(fig, master=self.window) self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=True) self.plot_current() buttons = Frame(window) lines = Checkbutton(buttons, text="Lines", variable=self.use_lines, command=self.plot_current) lines.pack(side=LEFT) points = Checkbutton(buttons, text="Points", variable=self.use_points, command=self.plot_current) points.pack(side=LEFT) generate = Button(buttons, text="Generate", command=self.do_generate) generate.pack(side=LEFT) buttons.pack(side=TOP, fill=X, expand=False)
def plotLightCurve(self, star): # clears anything that's already there self.clearLightCurve() self.clearText() self.showText(star) fluxes = [] times = self._app._timeInput.timeValues # get the fluxes from the table i = 1 while i <= len(times): fluxes.append(self.starTable[star]["flux" + str(i)]) i += 1 # plot the figure and set axis etc fig = Figure() fig.set_size_inches(5, 4, forward=True) self.a = fig.add_subplot(111) self.a.plot(times, fluxes, '-x') self.a.set_title("Light Curve for star " + str(star + 1), fontsize=11) self.a.set_ylabel("Change in Magnitude", fontsize=10) self.a.set_xlabel("Time (days)", fontsize=10) # rotate y axis numbers so it fits better for tick in self.a.get_yticklabels(): tick.set_rotation(65) fig.align_xlabels() self.a.tick_params(axis='x', labelsize=8) self.a.tick_params(axis='y', labelsize=8) self.lightCurve = FigureCanvasTkAgg(fig, master=self._app) self.lightCurve.get_tk_widget().place(relx=0.4, rely=0.4) self.lightCurve.draw()
class MplCanvas(Canvas): def __init__(self, parent=None, width=2, height=2, dpi=100): self.fig = Figure(figsize=(width, height), dpi=dpi) self.axes = self.fig.add_subplot(111) self.axes.tick_params(labelsize=15) self._w_inches = width self._h_inches = height self._dpi = dpi self.fig.subplots_adjust(left=0.15,right=0.95, bottom=0.15,top=0.95, hspace=0,wspace=0) Canvas.__init__(self, self.fig) self.setParent(parent) Canvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) Canvas.updateGeometry(self) def update_figure (self): pass def set_tick_fontsize (self, fontsize): self.axes.tick_params(labelsize=fontsize) def resize_canvas (self, w, h): self._w_inches = w/float(self._dpi) self._h_inches = h/float(self._dpi) self.fig.set_size_inches (self._w_inches, self._h_inches) self.draw() def clear (self): self.axes.clear()
class matplotPanel(wx.Panel): def __init__(self, drawfunc, parent, id, *args, **kwargs): super(matplotPanel, self).__init__(parent, id, *args, **kwargs) self.drawfunc = drawfunc self.parent = parent self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_PAINT, self.OnPaint) def _SetSize(self): # size = tuple(self.parent.GetClientSize()) size = tuple(self.GetClientSize()) # self.SetSize(size) self.figure = Figure(None) self.canvas = FigureCanvasWxAgg(self, wx.NewId(), self.figure) self.canvas.SetSize(size) dpi = self.figure.get_dpi() self.figure.set_size_inches(float(size[0]) / dpi, float(size[1]) / dpi) def OnSize(self, ev): self.Refresh() def OnPaint(self, ev): self._SetSize() dc = wx.PaintDC(self) # don't delete this line self.drawfunc(self)
def save_plotSpectrum(y,Fs,image_name): """ Plots a Single-Sided Amplitude Spectrum of y(t) """ fig = Figure(linewidth=0.0) fig.set_size_inches(fig_width,fig_length, forward=True) Figure.subplots_adjust(fig, left = fig_left, right = fig_right, bottom = fig_bottom, top = fig_top, hspace = fig_hspace) n = len(y) # length of the signal _subplot = fig.add_subplot(2,1,1) print "Fi" _subplot.plot(arange(0,n),y) xlabel('Time') ylabel('Amplitude') _subploti_2=fig.add_subplot(2,1,2) k = arange(n) T = n/Fs frq = k/T # two sides frequency range frq = frq[range(n/2)] # one side frequency range Y = fft(y)/n # fft computing and normalization Y = Y[range(n/2)] _subplot_2.plot(frq,abs(Y),'r') # plotting the spectrum xlabel('Freq (Hz)') ylabel('|Y(freq)|') print "here" canvas = FigureCanvasAgg(fig) if '.eps' in outfile_name: canvas.print_eps(outfile_name, dpi = 110) if '.png' in outfile_name: canvas.print_figure(outfile_name, dpi = 110)
class PanelPlot(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, style=wx.WS_EX_PROCESS_IDLE) ''', style = wx.NO_FULL_REPAINT_ON_RESIZE''' self.figure = Figure() self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.set_size() self.draw() self._resize_flag = False #self.Bind(wx.EVT_IDLE, self.on_idle) #self.Bind(wx.EVT_SIZE, self.on_size) def on_idle(self, event): #event.RequestMore() if self._resize_flag: self._resize_flag = False #wx.CallLater(500,self.set_size()) def on_size(self, event): self._resize_flag = True def set_size(self): pixels = tuple(self.GetSize()) self.SetSize(pixels) self.canvas.SetSize(pixels) self.figure.set_size_inches( [float(x) / self.figure.get_dpi() for x in pixels]) def draw(self): self.canvas.draw()
def plot_image(group): q = select([log_t.c.query_time, log_t.c.amount_in_queue], log_t.c.id == group_t.c.id) q = q.where(group_t.c.group_name == group) q = q.where(log_t.c.query_time >= datetime.now() - timedelta(hours=4)) q = q.order_by(log_t.c.query_time) thresh = Group.query.filter_by(group_name=group).first().surplus_threshold data = list(q.execute()) if len(data) < 1: return redirect(url_for('main_menu')) png_data = StringIO() # Zip() with a '*' is a projection, who knew? time, count = zip(*data) fig = Figure() fig.set_size_inches(11, 8.5) axis = fig.add_subplot(1, 1, 1) axis.plot(time, count, marker='.') axis.xaxis.set_major_formatter(DateFormatter('%m/%d %H:%M')) fig.autofmt_xdate() axis.axhline(thresh, color='red', linestyle='-.') canvas = FigureCanvas(fig) canvas.print_png(png_data) response = make_response(png_data.getvalue()) response.mimetype = 'image/png' return response
class MplAxes(object): def __init__(self, parent): self._parent = parent self._parent.resizeEvent = self.resize_graph self.create_axes() self.redraw_figure() def create_axes(self): self.figure = Figure(None, dpi=100) self.canvas = FigureCanvas(self.figure) self.canvas.setParent(self._parent) axes_layout = QtGui.QVBoxLayout(self._parent) axes_layout.setContentsMargins(0, 0, 0, 0) axes_layout.setSpacing(0) axes_layout.setMargin(0) axes_layout.addWidget(self.canvas) self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.canvas.updateGeometry() self.axes = self.figure.add_subplot(111) def resize_graph(self, event): new_size = event.size() self.figure.set_size_inches([new_size.width() / 100.0, new_size.height() / 100.0]) self.redraw_figure() def redraw_figure(self): self.figure.tight_layout(None, 0.8, None, None) self.canvas.draw()
def create_rose_date(station, date): if date == "": df = pd.read_csv( "https://greduvent.000webhostapp.com/sensations/get-meteo.php") else: df = pd.read_csv( "https://greduvent.000webhostapp.com/sensations/get-meteo.php?date=" + date) df.columns = [ 'date_heure', 'station', 'vent', 'orientation', 'temperature' ] df["date_heure"] = pd.to_datetime(df["date_heure"], format='%Y-%m-%d %H:%M') df[["vent", "orientation", "temperature"]] = df[["vent", "orientation", "temperature"]].apply(pd.to_numeric) df_station = df[df['station'] == station] fig = Figure() fig.set_size_inches(7, 7, forward=True) fig.suptitle(station) ax = fig.add_subplot(1, 1, 1, projection="windrose") wd = df_station['orientation'] ws = df_station['vent'] ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white') ax.set_legend() return fig
class MplCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=dpi): self.parent = parent self.fig = Figure(figsize=(10, 20), dpi=dpi, facecolor=(1, 1, 1), edgecolor=(0.5, 0, 0)) self.axes = self.fig.subplots(nrows=len(cmaps), ncols=1) # alignment of each subplot. self.fig.subplots_adjust( top=0.995, bottom=0.01, left=0.22, # leave room for the label naming this colour map right=0.98 # leave a small gap before edge of canvas ) # total size of canvas self.fig.set_size_inches(7, 40) # total size of canvas super(MplCanvas, self).__init__(self.fig) cid = self.fig.canvas.mpl_connect('button_press_event', self.on_press) def on_press(self, event): if event.inaxes is not None: self.parent.selcolmap = cmaps[ event.inaxes.get_subplotspec().rowspan.start] self.parent.updatelabel() self.parent.EnactColourMapSelection()
class MplAxes(object): def __init__(self, parent): self._parent = parent self._parent.resizeEvent = self.resize_graph self.create_axes() self.redraw_figure() def create_axes(self): self.figure = Figure(None, dpi=100) self.canvas = FigureCanvas(self.figure) self.canvas.setParent(self._parent) axes_layout = QtGui.QVBoxLayout(self._parent) axes_layout.setContentsMargins(0, 0, 0, 0) axes_layout.setSpacing(0) axes_layout.setMargin(0) axes_layout.addWidget(self.canvas) self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.canvas.updateGeometry() self.axes = self.figure.add_subplot(111) def resize_graph(self, event): new_size = event.size() self.figure.set_size_inches( [new_size.width() / 100.0, new_size.height() / 100.0]) self.redraw_figure() def redraw_figure(self): self.figure.tight_layout(None, 0.8, None, None) self.canvas.draw()
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())
class Plotter(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100): plt.rcParams.update({'font.size': 5}) plt.tight_layout() self.fig = Figure(figsize=(width/100.0, height/100.0), dpi=dpi) FigureCanvas.__init__(self, self.fig) self.setParent(parent) self.update_geometry(width,height) def update_geometry(self, width, height): self.fig.set_size_inches(width/100.0, height/100.0) self.axes = self.fig.add_subplot(111) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def plotLineGraph(self, r, ylabel, xlabel, title): self.axes.clear() self.axes.plot(r) self.axes.set_ylabel(ylabel, fontsize=7) self.axes.set_xlabel(xlabel, fontsize=7) self.axes.set_title(title, fontsize=8) self.axes.legend() self.draw()
def matplotlib_figure(width, height): """Create a Matplotlib figure with specified width and height for rendering. w Width of desired plot. h Height of desired plot. return A Matplotlib figure. """ try: from matplotlib.backends.backend_agg import FigureCanvasAgg except: paraview.print_error( "Error: Cannot import matplotlib.backends.backend_agg.FigureCanvasAgg" ) try: from matplotlib.figure import Figure except: paraview.print_error("Error: Cannot import matplotlib.figure.Figure") figure = Figure() figureCanvas = FigureCanvasAgg(figure) figure.set_dpi(72) figure.set_size_inches(float(width) / 72.0, float(height) / 72.0) return figure
def create_histogram(session_id): """ Create a Matplotlib figure for a histogram of speeds observed in one session todo: this query is basically run twice on the session page. find way to consolidate """ with open( os.path.join(app.root_path, 'queries/observations_histogram.sql'), 'r') as f: session_observations = pd.read_sql(text(f.read()), db.session.bind, params={'session_id': session_id}) session_observations['speed_value'] = session_observations.apply( lambda row: utilities.convert_to_speed_units( row.distance_meters, row.elapsed_seconds, row.speed_units), axis=1) fig = Figure() fig.set_size_inches(4, 4) axis = fig.add_subplot(1, 1, 1) axis.hist(session_observations['speed_value']) axis.yaxis.set_major_locator(MaxNLocator(integer=True)) axis.set_title('Histogram of Observed Speeds') axis.set_ylabel('Count of Vehicles') axis.set_xlabel(session_observations['speed_units'][0]) return fig
def mathTex_to_QPixmap(mathTex, fs): # ---- set up a mpl figure instance ---- fig = Figure() fig.patch.set_facecolor('none') fig.set_canvas(FigureCanvasAgg(fig)) renderer = fig.canvas.get_renderer() # ---- plot the mathTex expression ---- ax = fig.add_axes([0, 0, 1, 1]) ax.axis('off') ax.patch.set_facecolor('none') t = ax.text(0, 0, mathTex, ha='left', va='bottom', fontsize=fs) # ---- fit figure size to text artist ---- fwidth, fheight = fig.get_size_inches() fig_bbox = fig.get_window_extent(renderer) text_bbox = t.get_window_extent(renderer) tight_fwidth = text_bbox.width * fwidth / fig_bbox.width tight_fheight = text_bbox.height * fheight / fig_bbox.height fig.set_size_inches(tight_fwidth, tight_fheight) # ---- convert mpl figure to QPixmap ---- buf, size = fig.canvas.print_to_buffer() qimage = QtGui.QImage.rgbSwapped( QtGui.QImage(buf, size[0], size[1], QtGui.QImage.Format_ARGB32)) qpixmap = QtGui.QPixmap(qimage) return qpixmap
class MathTextLabel(QWidget): def __init__(self, mathText, parent=None, **kwargs): super(QWidget, self).__init__(parent, **kwargs) _l=QVBoxLayout(self) _l.setContentsMargins(0,0,0,0) _r,_g,_b,_a=self.palette().base().color().getRgbF() self._figure=Figure(edgecolor=(_r,_g,_b), facecolor=(_r,_g,_b)) self._canvas=FigureCanvas(self._figure) _l.addWidget(self._canvas) self.drawFigure(mathText) def drawFigure(self, mathText): self._figure.clear() _text=self._figure.suptitle(mathText, x=0.0, y=1.0, horizontalalignment='left', verticalalignment='top', size=QFont().pointSize()*2 ) self._canvas.draw() (_x0,_y0),(_x1,_y1)=_text.get_window_extent().get_points() _w=_x1-_x0; _h=_y1-_y0 self._figure.set_size_inches(_w/80, _h/80) self.setFixedSize(_w,_h)
class PlotPanel (wx.Panel): """The PlotPanel has a Figure and a Canvas. OnSize events simply set a flag, and the actual resizing of the figure is triggered by an Idle event.""" def __init__( self, parent, **kwargs ): from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.figure import Figure # initialize Panel if 'id' not in kwargs.keys(): kwargs['id'] = wx.ID_ANY if 'style' not in kwargs.keys(): kwargs['style'] = wx.NO_FULL_REPAINT_ON_RESIZE wx.Panel.__init__( self, parent, **kwargs ) # initialize matplotlib stuff self.figure = Figure() self.canvas = FigureCanvasWxAgg( self, -1, self.figure ) self._SetSize() self.draw() #self.Bind(wx.EVT_IDLE, self._onIdle) self.Bind(wx.EVT_SIZE, self._onSize) def _onSize( self, event ): self._SetSize() def _SetSize( self ): pixels = tuple( self.parent.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 draw(self): pass # abstract, to be overridden by child classes
def mathTex_to_QPixmap(mathTex, fs): ''' E/ mathTEx : The formula to be displayed on screen in LaTeX E/ fs : The desired font size S/ qpixmap : The image to be displayed in Qpixmap format ''' # Set up a mpl figure instance # fig = Figure() fig.patch.set_facecolor('none') fig.set_canvas(FigureCanvas(fig)) renderer = fig.canvas.get_renderer() # Plot the mathTex expression # ax = fig.add_axes([0, 0, 1, 1]) ax.axis('off') ax.patch.set_facecolor('none') t = ax.text(0, 0, mathTex, ha='left', va='bottom', fontsize=fs) # Fit figure size to text artist # fwidth, fheight = fig.get_size_inches() fig_bbox = fig.get_window_extent(renderer) text_bbox = t.get_window_extent(renderer) tight_fwidth = text_bbox.width * fwidth / fig_bbox.width tight_fheight = text_bbox.height * fheight / fig_bbox.height fig.set_size_inches(tight_fwidth, tight_fheight) # Convert mpl figure to QPixmap # buf, size = fig.canvas.print_to_buffer() qimage = QtGui.QImage.rgbSwapped(QtGui.QImage(buf, size[0], size[1], QtGui.QImage.Format_ARGB32)) qpixmap = QtGui.QPixmap(qimage) return qpixmap
def create_seaborn_fig_from_data_and_definition(data, plot_options): # plot_options[LAYOUT] define figure level formatting: # figure size, number and arrangement of subplots, background, spines, axlabels # get user defined values, and update with default values layout_dict = plot_options.get(LAYOUT, {}) for viz_key, default_value in DEFAULT_LAYOUT_OPTIONS.items(): if viz_key not in layout_dict: layout_dict[viz_key] = default_value plot_options[LAYOUT] = layout_dict nrows = layout_dict[NROWS] ncols = layout_dict[NCOLS] fig = Figure(figsize=layout_dict[FIGSIZE]) for ind in range(1, nrows * ncols + 1): fig.add_subplot(nrows, ncols, ind) fig.set_size_inches(layout_dict[FIGSIZE]) for plot_ind, plot_definition in enumerate(plot_options["data"]): ax = fig.axes[plot_ind] # get the seaborn plotting function from the seaborn library based on the name plot_type = plot_definition.pop(TYPE) if plot_type in forbidden_plots: raise ValueError(f"{plot_type} not supported yet") plot_function = getattr(sns, plot_type) # separate out fig/ax parameters from seaborn function parameters g = plot_function(data=data, ax=ax, **plot_definition) # ax.legend(bbox_to_anchor=(1.1, 0.9), ncol=1) # g.legend(loc='center left', bbox_to_anchor=(1.1, 0.9), ncol=1) return fig
def plot_standard_curve(result, encoding='jpg'): if not result.isCalibrated: raise Exception('Can not plot standard curve if experiment is not calibrated.') fig = Figure() ax1 = fig.add_subplot(111) fig.set_size_inches(_plot_size[0],_plot_size[1], forward=True) fig.set_facecolor(plot_bgcolor) ax1.set_title('fitted curve') ax1.grid(True) background_mean, background_std = result.background_intensity # avoid division by zero with perfect testing images if background_mean == 0: print('warning: background is zero') background_mean = np.float64(1e-8) calibX, calibY = result.calibration_data calibY_snr = calibY / background_mean calibY_snr_err = result.intensity_stddev[result.calibration_data_indices] / background_mean curve = fittedCurve(calibX, calibY_snr) # plot fitted curve x = np.linspace(0,np.max(calibX),10) y = map(curve,x) ax1.plot(x, y, color='black', linewidth=1, label='fitted curve') # plot calibration points #ax1.plot(calibX, calibY_snr, marker='x', color='black', linewidth=0) #, yerr=calibY_snr_err) ax1.errorbar(calibX, calibY_snr, yerr=calibY_snr_err, marker='x', color='black', linewidth=0) ax1.set_xlabel('concentration [%s]'%_concentration_units) ax1.set_ylabel('signal / background') if background_std > 0: # don't plot lod, and loq if std_dev of background is not known. # limit of detection lod = result.limit_of_detection / background_mean ax1.axhline(y=lod, linewidth=1, color='g', label='LoD', linestyle='--') # limit of quantification loq = result.limit_of_quantification / background_mean ax1.axhline(y=loq, linewidth=1, color='b', label='LoQ', linestyle='-.') ax1.legend(loc=0) #plt.margins(0.2) #fig.subplots_adjust(hspace=0.2, wspace=0.2, bottom=0.15) #fig.tight_layout() return fig
class PlotPanel (wx.Panel): """ PlotPanel class taken from http://www.scipy.org/Matplotlib_figure_in_a_wx_panel The PlotPanel has a Figure and a Canvas. OnSize events simply set a flag, and the actual resizing of the figure is triggered by an Idle event.""" def __init__(self, parent, color=None, dpi=None, **kwargs): from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.figure import Figure self.parent = parent # initialize Panel if 'id' not in list(kwargs.keys()): kwargs['id'] = wx.ID_ANY if 'style' not in list(kwargs.keys()): kwargs['style'] = wx.NO_FULL_REPAINT_ON_RESIZE wx.Panel.__init__(self, parent, **kwargs) # initialize matplotlib stuff self.figure = Figure(None, dpi) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.SetColor(color) self._SetSize() self.draw() self._resizeflag = False self.Bind(wx.EVT_IDLE, self._onIdle) self.Bind(wx.EVT_SIZE, self._onSize) def SetColor(self, rgbtuple=None): """Set figure and canvas colours to be the same.""" if rgbtuple is None: rgbtuple = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE).Get() clr = [c / 255. for c in rgbtuple] self.figure.set_facecolor(clr) self.figure.set_edgecolor(clr) self.canvas.SetBackgroundColour(wx.Colour(*rgbtuple)) def _onSize(self, event): self._resizeflag = True def _onIdle(self, evt): if self._resizeflag: self._resizeflag = False self._SetSize() def _SetSize(self): pixels = tuple(self.parent.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 draw(self): # abstract, to be overridden by child classes raise NotImplementedError( "Abstract method - must be defined in subclass")
class GraphFrame(tk.Frame): def __init__(self, root, **kw): self.root = root tk.Frame.__init__(self, self.root, kw) # создание полей под объекты GUI self.frame, self.f_1, self.ax0, self.label_font, self.f_1_canvas = None, None, None, None, None self.pause_button = None self.data, self.legend = [["Имя 0", [1, 2, 3], "Name 0"]], None self.table = None self._show_time = 1000 self.show_time_var, self.show_time_label, self.show_time_entry = None, None, None self.gui_set() self.x_label = "Напряжение ЗС, В" self.y_label = "Ток МПЗ, А" def gui_set(self): # graph self.frame = tk.Frame(self, bg="gray10") self.frame.place(x=10, y=10, relwidth=1, relheight=1, width=-20, height=-40) self.f_1 = Figure(figsize=(6.5, 5.5), dpi=100, facecolor="#A9A9A9", frameon=True) self.ax0 = self.f_1.add_axes((0.1, 0.15, 0.88, 0.83), facecolor="#D3D3D3", frameon=True, yscale="linear") self.label_font = {'family': 'Arial', 'color': 'Black', 'weight': 'normal', 'size': 12, } self.f_1_canvas = FigureCanvasTkAgg(self.f_1, master=self.frame) self.f_1_canvas.get_tk_widget().pack(fill="both", expand=1) self.f_1_canvas.draw() self.resize() toolbar = NavigationToolbar2Tk(self.f_1_canvas, self) toolbar.place(x=0, rely=1, y=-35) toolbar.update() def resize(self): self.frame.update_idletasks() dx = self.frame.winfo_width() dy = self.frame.winfo_height() if dx > 1 and dx > 1: try: frame_info = self.frame.place_info() dpi = self.f_1.get_dpi() f_1_height = (float(frame_info["relheight"]) * dy + float(frame_info["height"])) / dpi f_1_width = (float(frame_info["relwidth"]) * dx + float(frame_info["width"])) / dpi self.f_1.set_size_inches(f_1_width, f_1_height) except: pass self.f_1_canvas.show() # self.f_1_canvas.get_tk_widget().pack(fill="both", expand=1) pass def plot(self, *arg, **kw): self.ax0.cla() self.ax0.plot(*arg, **kw) self.ax0.set_xlabel(self.x_label) self.ax0.set_ylabel(self.y_label) self.ax0.grid(which="both") self.f_1_canvas.draw() pass
def draw_heatmaps(case_data, project, timestamp, diced_meta_dir): rownames, matrix = _build_heatmap_matrix(case_data) # def draw_heatmaps(rownames, matrix, cohort, timestamp, outputDir): if not len(matrix) > 0: raise ValueError('input matrix must have nonzero length') if not len(matrix) == len(rownames): raise ValueError('Number of row names does not match input matrix') #Sort heatmaps rows by row count sorted_rownames, sorted_matrix = __sort_rows(rownames, matrix) green = '#338855' white = '#FFFFFF' cmap = ListedColormap([white, green]) fig = Figure(figsize=(24, 12)) ax = fig.add_subplot(111) ax.set_title("%s: Data Type Breakdown by Participant" % project, weight="black") ax.set_ylabel("Data Type (Total Sample Count)", weight="black") ax.set_xlabel("Participant", weight="black") ax.set_xlim(0, len(sorted_matrix[0])) ax.set_yticks([0.5 + x for x in range(len(sorted_matrix))]) counts = [sum(row) for row in sorted_matrix] ax.set_yticklabels([ "%s (%s)" % (data_type, count) for data_type, count in zip(sorted_rownames, counts) ]) ax.pcolor(numpy.array(sorted_matrix), cmap=cmap, norm=NoNorm(), edgecolor="k") missing = Rectangle((0, 0), 1, 1, fc=white) present = Rectangle((0, 0), 1, 1, fc=green) ax.legend([present, missing], ["Present", "Absent"], loc=1) fig.set_size_inches(24, 12) ax.title.set_size("xx-large") ax.xaxis.label.set_size("xx-large") ax.yaxis.label.set_size("xx-large") ax.tick_params(axis="both", labelsize="x-large") canvas = FigureCanvasAgg(fig) high_res_filepath = os.path.join( diced_meta_dir, ".".join([project, timestamp, "high_res.heatmap.png"])) fig.tight_layout() canvas.print_figure(high_res_filepath) fig.set_size_inches(12, 6) ax.title.set_size("medium") ax.xaxis.label.set_size("small") ax.yaxis.label.set_size("small") ax.tick_params(axis="both", labelsize="x-small") fontProp = font_manager.FontProperties(size=9) ax.legend([present, missing], ["Present", "Absent"], loc=1, prop=fontProp) canvas = FigureCanvasAgg(fig) low_res_filepath = os.path.join( diced_meta_dir, ".".join([project, timestamp, "low_res.heatmap.png"])) fig.tight_layout() canvas.print_figure(low_res_filepath)
def init_gui(self): self.builder = Gtk.Builder() self.builder.add_from_file("finally.glade") self.builder.connect_signals( { "window_destroy" : self.window_destroy, "press_button" : self.press_button, "clear_text" : self.clear_text, "remove_last_char": self.remove_last_char, "calculate" : self.calculate, "switch_page" : self.switch_page, "num_base_change" : self.num_base_change, "fix_cursor" : self.fix_cursor, "enable_textview" : self.enable_textview, "disable_textview": self.disable_textview, "prog_calc" : self.prog_calc, "back_to_future" : self.back_to_future, "plot" : self.plot } ) self.window = self.builder.get_object("main_window") self.window.set_size_request(250,305) self.window.set_title("The Calculator") self.window.set_icon_from_file("/usr/share/pixmaps/thecalculator-icon.png") self.text_buff = self.builder.get_object("class_17").get_buffer() # Access buffer from TextView self.builder.get_object("class_17").grab_focus() self.builder.get_object("radiobutton3").set_active(True) self.num_base_change(self.builder.get_object("radiobutton3")) ############### PLOT FUNCTION ############## sw = self.builder.get_object("scrolledwindow1") sw2 = self.builder.get_object("scrolledwindow2") fig = Figure(figsize=(5,5),dpi=120) self.ax = fig.add_subplot(111) self.x = arange(-3.1415,3.1415,0.01) self.y = sin(self.x) self.ax.plot(self.x,self.y,label="sin(x)") self.ax.set_xlim(-3.2,3.2) self.ax.set_ylim(-1.2,1.2) self.ax.grid(True) fig.set_size_inches(9.5, 5.5, forward=True) fig.tight_layout() self.canvas = FigureCanvas(fig) sw.add_with_viewport(self.canvas) self.canvas.show() toolbar = NavigationToolbar(self.canvas, self.window) sw2.add_with_viewport(toolbar)
def create_img(self, filename): fig = Figure() canvas = FigureCanvas(fig) self.build(fig) fig.set_frameon(False) # Background is hidden fig.set_size_inches(self.size[0], self.size[1]) # Set size fig.savefig(filename, dpi=self.dpi)
class myWxPlot(wx.Panel): def __init__( self, parent): from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.figure import Figure self.parent = parent wx.Panel.__init__( self, parent) #matplotlib figure self.figure = Figure( None ) self.figure.set_facecolor( (0.7,0.7,1.) ) self.subplot = self.figure.add_subplot( 111 ) #canvas self.canvas = FigureCanvasWxAgg( self, -1, self.figure ) self.canvas.SetBackgroundColour( wx.Color( 100,255,255 ) ) self._SetSize() self.draw() def _SetSize( self ): size = tuple( self.parent.GetClientSize() ) self.SetSize( size ) self.canvas.SetSize( size ) self.figure.set_size_inches( float( size[0] )/self.figure.get_dpi(), float( size[1] )/self.figure.get_dpi() ) def draw(self): from mpl_toolkits.mplot3d import Axes3D import numpy as np x = np.arange(-3, 3, 0.25) y = np.arange(-3, 3, 0.25) X, Y = np.meshgrid(x, y) Z = np.sin(X)+ np.cos(Y) ax = Axes3D(self.figure) ax.plot_wireframe(X,Y,Z) # 2次元のグラフを描画するコードが次の例です。subplotにグラフをplotしています。 def draw(self): import numpy as np theta = np.arange(0,200, 0.1) x = 2*np.cos(theta/7) y = 3*np.sin(theta/3) self.subplot.plot(x,y, '-r') self.subplot.set_title("Sample", fontsize = 12) self.subplot.set_xlabel("x") self.subplot.set_ylabel("y") self.subplot.set_xlim([-4, 4]) self.subplot.set_ylim([-4, 4])
def print_( self, printer ): from matplotlib.figure import Figure from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas rect = printer.pageRect( QtGui.QPrinter.Inch ) dpi = printer.resolution() fig = Figure( facecolor='#ffffff') fig.set_size_inches( ( rect.width(), rect.height() ) ) fig.set_dpi( dpi ) self.chart.plot_on_figure( fig ) canvas = FigureCanvas( fig ) canvas.render( printer )
class MatplotlibPanel(wx.Panel): def __init__(self,parent,ID=-1,label="",pos=wx.DefaultPosition,size=(100,25)): self.parent = parent #(0) Initialize panel: wx.Panel.__init__(self,parent,ID,pos,size,wx.STATIC_BORDER,label) self.SetMinSize(size) #(1) Create Matplotlib figure: self.figure = Figure(facecolor=(0.8,)*3) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self._resize() self._create_axes() self.cidAxisEnter = self.canvas.mpl_connect('axes_enter_event', self.callback_enter_axes) self.cidAxisLeave = self.canvas.mpl_connect('axes_leave_event', self.callback_leave_axes) def _create_axes(self): self.ax = self.figure.add_axes((0,0,1,1), axisbg=[0.5]*3) pyplot.setp(self.ax, xticks=[], yticks=[]) def _resize(self): szPixels = tuple( self.GetClientSize() ) self.canvas.SetSize(szPixels) szInches = float(szPixels[0])/self.figure.get_dpi() , float(szPixels[1])/self.figure.get_dpi() self.figure.set_size_inches( szInches[0] , szInches[1] ) def callback_enter_axes(self, event): self.parent.parent.panel_enter(event, panel=self.parent) def callback_leave_axes(self, event): self.parent.parent.panel_leave(event) def cla(self): self.ax.cla() self.ax.set_position([0,0,1,1]) self.ax.set_axis_bgcolor([0.5]*3) pyplot.setp(self.ax, xticks=[], yticks=[], xlim=(0,1), ylim=(0,1)) self.ax.axis('tight') self.canvas.draw() def plot(self, I0, I, cmax=None, pois=None): if I!=None: if cmax==None: cmax = I.max() I[I==0] = np.nan self.ax.imshow(I, interpolation='nearest', origin='lower', vmin=0, vmax=cmax) self.ax.contour(I0>0, 1, colors="0.5", linewidths=1) pyplot.setp(self.ax, xticks=[], yticks=[]) self.ax.set_axis_bgcolor([0.05]*3) self.ax.axis('image') if pois!=None: for i,(x,y) in enumerate(pois): self.ax.plot(x, y, 'wo', markersize=8) self.ax.text(x+1, y+1, '%d'%(i+1), bbox=dict(facecolor='w')) self.canvas.draw()
def plot_categorized(result, encoding='jpg'): fig = Figure() ax1 = fig.add_subplot(111) categoryMap = result.categoryMap categorized = result.categorized isCalibrated = result.isCalibrated labels = categorized.keys() labels = sorted(labels, key=lambda l: categorized[l]) x = np.arange(len(labels))+1 values = np.array(result.concentration_values) avgValues = [categorized[k] for k in labels] fig.set_size_inches(_plot_size[0],_plot_size[1], forward=True) fig.set_facecolor(plot_bgcolor) ax1.set_title('results') ax1.grid(True) # plot all values i = 0 for cat in labels: indices = [idx for idx, c in categoryMap.items() if c==cat] y = values[indices] ax1.plot([x[i]]*len(y), y, marker='x', color='gray', linewidth=0) i = i+1 # plot mean values ax1.plot(x, avgValues, marker='o', color='black', linewidth=0) #ax1.set_xticks(x, labels, rotation='horizontal') ax1.set_xticks(x, labels) ax1.legend(loc=4) fig.subplots_adjust(hspace=0.2, wspace=0.2, bottom=0.15) ax1.set_xlabel('category') if isCalibrated: ax1.set_ylabel('concentration [%s]'%_concentration_units) else: ax1.set_ylabel('intensity') #fig.tight_layout() return fig
class MatplotlibPanel(wx.Panel): def __init__(self,parent,ID=-1,label="",pos=wx.DefaultPosition,size=(100,25)): self.parent = parent #(0) Initialize panel: wx.Panel.__init__(self,parent,ID,pos,size,wx.STATIC_BORDER,label) self.SetMinSize(size) self.parent = parent #(1) Create Matplotlib figure: self.figure = Figure(facecolor=(0.8,)*3) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self._resize() self._create_axes() self.cidAxisEnter = self.canvas.mpl_connect('axes_enter_event', self.callback_enter_axes) self.cidAxisLeave = self.canvas.mpl_connect('axes_leave_event', self.callback_leave_axes) #self.Bind(wx.EVT_ENTER_WINDOW, self.callback_enter_axes) self.Bind(wx.EVT_LEAVE_WINDOW, self.callback_leave_axes) def _create_axes(self): self.ax = self.figure.add_axes((0,0,1,1), axisbg=[0.5]*3) pyplot.setp(self.ax, xticks=[], yticks=[]) def _resize(self): szPixels = tuple( self.GetClientSize() ) self.canvas.SetSize(szPixels) szInches = float(szPixels[0])/self.figure.get_dpi() , float(szPixels[1])/self.figure.get_dpi() self.figure.set_size_inches( szInches[0] , szInches[1] ) def callback_enter_axes(self, event): self.parent.parent.panel_enter(event, panel=self.parent) def callback_leave_axes(self, event): self.parent.parent.panel_leave(event) def cla(self): self.ax.cla() self.ax.set_position([0,0,1,1]) self.ax.set_axis_bgcolor([0.5]*3) pyplot.setp(self.ax, xticks=[], yticks=[], xlim=(0,1), ylim=(0,1)) self.ax.axis('tight') self.canvas.draw() def plot(self, I, cmax=None): if I!=None: if cmax==None: cmax = I.max() I[I==0] = np.nan self.ax.imshow(I, interpolation='nearest', origin='lower', vmin=0, vmax=cmax) pyplot.setp(self.ax, xticks=[], yticks=[]) self.ax.set_axis_bgcolor([0.05]*3) self.ax.axis('image') self.canvas.draw()
class WXMatPlotLibPanel( wx.Panel ): def __init__( self, parent, color=None, dpi=None, **kwargs ): from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.figure import Figure # initialize Panel if 'id' not in kwargs.keys(): kwargs['id'] = wx.ID_ANY if 'style' not in kwargs.keys(): kwargs['style'] = wx.NO_FULL_REPAINT_ON_RESIZE wx.Panel.__init__( self, parent, **kwargs ) # initialize matplotlib stuff self.figure = Figure( None, dpi ) self.canvas = FigureCanvasWxAgg( self, -1, self.figure ) #self.SetColor( color ) self._SetSize() self.draw() self._resizeflag = False self.Bind(wx.EVT_IDLE, self._onIdle) self.Bind(wx.EVT_SIZE, self._onSize) def SetColor( self, rgbtuple=None ): """Set figure and canvas colours to be the same.""" if rgbtuple is None: rgbtuple = wx.SystemSettings.GetColour( wx.SYS_COLOUR_BTNFACE ).Get() clr = [c/255. for c in rgbtuple] self.figure.set_facecolor( clr ) self.figure.set_edgecolor( clr ) self.canvas.SetBackgroundColour( wx.Colour( *rgbtuple ) ) def _onSize( self, event ): self._resizeflag = True def _onIdle( self, evt ): if self._resizeflag: self._resizeflag = False self._SetSize() def _SetSize( self ): pixels = tuple( self.parent.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 draw(self): pass # abstract, to be overridden by child classes
def create_figure(figname): """Create a matplotlib figure, save it to disk and return its data.""" # Create and save to disk a figure with matplotlib. fig = Figure() canvas = FigureCanvasAgg(fig) ax = fig.add_axes([0.15, 0.15, 0.7, 0.7]) fig.set_size_inches(6, 4) ax.plot(np.random.rand(10), '.', color='red') fig.savefig(figname) # Read back and return the binary data from the file. with open(figname, "rb") as img: fig = img.read() return fig
class CheckMeansPanel(wx.Panel): def __init__(self,parent,ID=-1,label="",pos=wx.DefaultPosition,size=(100,25)): #(0) Initialize panel: wx.Panel.__init__(self,parent,ID,pos,size,wx.STATIC_BORDER,label) self.SetMinSize(size) #(1) Create Matplotlib figure: self.figure = Figure(facecolor=(0.8,)*3) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self._resize() self._create_axes() # self.cidAxisEnter = self.canvas.mpl_connect('axes_enter_event', self.callback_enter_axes) # self.cidAxisLeave = self.canvas.mpl_connect('axes_leave_event', self.callback_leave_axes) def _create_axes(self): self.ax = self.figure.add_axes((0,0,1,1), axisbg=[0.5]*3) self.cax = self.figure.add_axes((0.1,0.05,0.8,0.02), axisbg=[0.5]*3) pyplot.setp(self.ax, xticks=[], yticks=[]) def _resize(self): szPixels = tuple( self.GetClientSize() ) self.canvas.SetSize(szPixels) szInches = float(szPixels[0])/self.figure.get_dpi() , float(szPixels[1])/self.figure.get_dpi() self.figure.set_size_inches( szInches[0] , szInches[1] ) # def callback_enter_axes(self, event): # print 'buta-san in' # def callback_leave_axes(self, event): # print 'buta-san out' def cla(self): self.ax.cla() self.cax.cla() # self.ax.set_position([0,0,1,1]) self.ax.set_axis_bgcolor([0.5]*3) pyplot.setp(self.ax, xticks=[], yticks=[], xlim=(0,1), ylim=(0,1)) self.ax.axis('tight') self.canvas.draw() def plot(self, I): I = np.asarray(I, dtype=float) I[I==0] = np.nan self.ax.imshow(I, interpolation='nearest', origin='lower') pyplot.setp(self.ax, xticks=[], yticks=[]) self.ax.set_axis_bgcolor([0.05]*3) self.ax.axis('image') cb = pyplot.colorbar(cax=self.cax, mappable=self.ax.images[0], orientation='horizontal') pyplot.setp(cb.ax.get_xticklabels(), color='0.5') self.canvas.draw()
def plot_signal_to_noise(result, encoding='jpg', show=False): fig = Figure() ax1 = fig.add_subplot(111) fig.set_size_inches(_plot_size[0],_plot_size[1], forward=True) fig.set_facecolor(plot_bgcolor) ax1.set_title('Signal to Background') ax1.grid(True) background_mean, background_std = result.background_intensity # avoid division by zero with perfect testing images if background_mean == 0: print('warning: background is zero') background_mean = np.float64(1e-8) y = result.intensity_values x = np.arange(len(y))+1 y_snr = y / background_mean y_snr_err = result.intensity_stddev / background_mean ax1.errorbar(x, y_snr, yerr=y_snr_err, marker='x', color='black', linewidth=0) ax1.set_xlabel('spot') ax1.set_ylabel('signal / background') if background_std > 0: # don't plot lod, and loq if std_dev of background is not known. # limit of detection lod = result.limit_of_detection / background_mean ax1.axhline(y=lod, linewidth=1, color='g', label='LoD', linestyle='--') # limit of quantification loq = result.limit_of_quantification / background_mean ax1.axhline(y=loq, linewidth=1, color='b', label='LoQ', linestyle='-.') ax1.legend(loc=4) #fig.tight_layout() return fig
def cosmo_contour(x, y, avg, min, max, neventsUL, filename): fig = Figure() FigureCanvas(fig) fig.set_size_inches(4.5, 4.5) axes = fig.add_axes((.12, .15, .98 - .12, .90 - .15)) axes.loglog() axes.contour(x, y, avg, [neventsUL], linestyles='solid', colors='r') axes.contour(x, y, min, [neventsUL], linestyles='dashed', colors='r') axes.contour(x, y, max, [neventsUL], linestyles='dashed', colors='r') axes.set_xlim([x.min(),x.max()]) axes.set_ylim([y.min(),y.max()]) axes.set_title(r"95\% upper limit") axes.set_xlabel(r"$G\mu$") axes.set_ylabel(r"$p$") fig.savefig(filename)
def plot_coefficients(picid, coeffs, psc_dir): fig = Figure() FigureCanvas(fig) fig.set_size_inches(9, 6) ax = fig.add_subplot(111) ax.plot(coeffs) ax.set_xlabel('Reference Index') ax.set_ylabel('Coefficient Value') fig.suptitle(f'Reference coeffecients - {picid}') coeff_fn = os.path.join(psc_dir, 'plots', f'coefficients-{picid}.png') fig.savefig(coeff_fn, transparent=False)
def paint(self, grammar_estimator, path, configuration): data = grammar_estimator[self.criteria] steps = range(configuration.max_algorithm_steps) x = [] y = [] x_min = [] y_min = [] x_max = [] y_max = [] for step in steps: value = data.get(step) min_value = data.get_min(step) max_value = data.get_max(step) if not math.isnan(value): y.append(value) x.append(step) if not math.isnan(min_value): y_min.append(min_value) x_min.append(step) if not math.isnan(max_value): y_max.append(max_value) x_max.append(step) fig = Figure() canvas = FigureCanvasAgg(fig) ax = fig.add_axes([.1, .1, .8, .8], title='{0}/steps'.format(self.criteria)) self._plot_line(ax, x_min, y_min, 'dashed', self.criteria + '_min', no_points=True, color='cyan') self._plot_line(ax, x_max, y_max, 'dashed', self.criteria + '_max', no_points=True, color='cyan') self._plot_line(ax, x, y, 'solid', self.criteria) font_p = FontProperties() font_p.set_size('small') ax.legend(prop=font_p, loc='best') if not x: ax.text(0, 0, 'No data to generate valid diagram', style='italic', bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10}) fig.set_size_inches(22, 12) fig.savefig(os.path.join(path, self.out_name + self.DIAGRAM_EXT), dpi=60)