def plotSolarRadiationAgainstMonth(filename): trainRowReader = csv.reader(open(filename, 'rb'), delimiter=',') month_most_common_list = [] Solar_radiation_64_list = [] for row in trainRowReader: month_most_common = row[3] Solar_radiation_64 = row[6] month_most_common_list.append(month_most_common) Solar_radiation_64_list.append(Solar_radiation_64) #convert all elements in the list to float while skipping the first element for the 1st element is a description of the field. month_most_common_list = [float(i) for i in prepareList(month_most_common_list)[1:] ] Solar_radiation_64_list = [float(i) for i in prepareList(Solar_radiation_64_list)[1:] ] fig=Figure() ax=fig.add_subplot(111) title='Scatter Diagram of solar radiation against month of the year' ax.set_xlabel('Most common month') ax.set_ylabel('Solar Radiation') fig.suptitle(title, fontsize=14) try: ax.scatter(month_most_common_list, Solar_radiation_64_list) #it is possible to make other kind of plots e.g bar charts, pie charts, histogram except ValueError: pass canvas = FigureCanvas(fig) canvas.print_figure('solarRadMonth.png',dpi=500)
def __get_column_width(self): max_length = 0 max_column_text = '' flag = self.prefs.get('legend_numbers',True) unit = self.prefs.get('legend_unit',False) for label,num in self.labels: if not flag: num = None if num is not None: column_length = len(str(label)+str(num)) + 1 else: column_length = len(str(label)) + 1 if column_length > max_length: max_length = column_length if flag: if type(num) == types.IntType or type(num) == types.LongType: numString = str(num) else: numString = "%.1f" % float(num) max_column_text = '%s %s' % (str(label),numString) if unit: max_column_text += "%" else: max_column_text = '%s ' % str(label) figure = Figure() canvas = FigureCanvasAgg(figure) dpi = self.prefs['dpi'] figure.set_dpi( dpi ) l_size,l_padding = self.__get_legend_text_size() self.text_size = pixelToPoint(l_size,dpi) text = Text(0.,0.,text=max_column_text,size=self.text_size) text.set_figure(figure) bbox = text.get_window_extent(canvas.get_renderer()) self.column_width = bbox.width+6*l_size
def init_window(self): if self.window: return self.window = Gtk.Window(title="Subplot Configuration Tool") try: self.window.window.set_icon_from_file(window_icon) except Exception: # we presumably already logged a message on the # failure of the main plot, don't keep reporting pass self.vbox = Gtk.Box() self.vbox.set_property("orientation", Gtk.Orientation.VERTICAL) self.window.add(self.vbox) self.vbox.show() self.window.connect('destroy', self.destroy) toolfig = Figure(figsize=(6, 3)) canvas = self.figure.canvas.__class__(toolfig) toolfig.subplots_adjust(top=0.9) SubplotTool(self.figure, toolfig) w = int(toolfig.bbox.width) h = int(toolfig.bbox.height) self.window.set_default_size(w, h) canvas.show() self.vbox.pack_start(canvas, True, True, 0) self.window.show()
def __init__(self, viewer, selected): self.selected = selected self.ids = [str(i) + " - " + str(s) for i, s in enumerate(selected)] t2 = Tk.Toplevel(viewer) t2.title('Data Range Editor') t2.transient(viewer) # Image selection combobox sel_fr = Tk.Frame(master=t2) Tk.Label(sel_fr, text="Image:").pack(side=Tk.LEFT) self.imagesel = ttk.Combobox(sel_fr) self.imagesel['values'] = [str(s) for s in selected] self.imagesel.bind('<<ComboboxSelected>>', self.update) im = self.selected[0] self.imagesel.set(self.ids[0]) self.imagesel.pack(side=Tk.LEFT) sel_fr.pack(side=Tk.TOP) # Grid showing current vmin, vmax and original vmin,vmax lim_fr = Tk.Frame(master=t2) Tk.Label(lim_fr, text="Upper limit:").grid(row=1,column=1) Tk.Label(lim_fr, text="Lower limit:").grid(row=2,column=1) self.ulim_orig, self.llim_orig = Tk.StringVar(), Tk.StringVar() self.ulim, self.llim = Tk.StringVar(), Tk.StringVar() self.upper_limit = Tk.Entry(lim_fr, textvariable=self.ulim) self.lower_limit = Tk.Entry(lim_fr, textvariable=self.llim) self.upper_limit.grid(row=1,column=2) self.lower_limit.grid(row=2,column=2) upper_limit_orig = Tk.Entry(lim_fr, textvariable=self.ulim_orig, state=Tk.DISABLED) lower_limit_orig = Tk.Entry(lim_fr, textvariable=self.llim_orig, state=Tk.DISABLED) upper_limit_orig.grid(row=1,column=3) lower_limit_orig.grid(row=2,column=3) lim_fr.pack(side=Tk.BOTTOM, fill=Tk.NONE, expand=0) # Button frame buttons = Tk.Frame(master=t2) self.all_images = Tk.BooleanVar() self.all_images.set(False) Tk.Checkbutton(buttons, text="Apply to all images", variable=self.all_images).pack(side=Tk.TOP) apply = Tk.Button(master=buttons, text='Apply', command=self.set_limits) apply.pack(side=Tk.RIGHT) reset = Tk.Button(master=buttons, text='Reset', command=self.reset) reset.pack(side=Tk.RIGHT) buttons.pack(side=Tk.BOTTOM, fill=Tk.NONE, expand=0) # Matplotlib figure f = Figure(figsize=(5,4), dpi=100) self.a = f.add_subplot(111) self.canvas = FigureCanvasTkAgg(f, master=t2) self.canvas.show() self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.update()
class WattrGraphPanel( WattrGUI.GraphPanel ): subplot = 0 plots = {} def __init__(self, parent, fgsize=None, dpi=None): super(WattrGraphPanel, self).__init__(parent) self.figure = Figure(fgsize, dpi) #Transparent figure face color self.figure.set_facecolor((0,0,0,0,)) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) # Now put all into a sizer sizer = self.GetSizer() # This way of adding to sizer allows resizing sizer.Add(self.canvas, 1, wx.LEFT|wx.TOP|wx.GROW) # Best to allow the toolbar to resize! self.toolbar = NavigationToolbar2Wx(self.canvas) self.toolbar.Realize() sizer.Add(self.toolbar, 0, wx.GROW) self.Fit() def add_plot(self, x=1, y=1): self.subplot += 1 plot = self.figure.add_subplot(x, y, self.subplot) plot.ticklabel_format(axis='y', style='plain', useOffset=False) plot.ticklabel_format(axis='x', style='plain', useOffset=False) self.plots[self.subplot] = plot return plot def draw(self): self.canvas.draw()
def addedRecently(self, numdays=30, attr='created'): self.calcStats() days = {} fig = Figure(figsize=(self.width, self.height), dpi=self.dpi) limit = self.endOfDay - (numdays) * 86400 res = self.deck.s.column0("select %s from cards where %s >= %f" % (attr, attr, limit)) for r in res: d = int((r - self.endOfDay) / 86400.0) days[d] = days.get(d, 0) + 1 self.addMissing(days, -numdays+1, 0) graph = fig.add_subplot(111) intervals = self.unzip(days.items()) if attr == 'created': colour = addedC else: colour = firstC self.varGraph(graph, numdays, colour, *intervals) graph.set_xlim(xmin=-numdays+1, xmax=1) graph.set_xlabel("Day (0 = today)") if attr == 'created': graph.set_ylabel("Cards Added") else: graph.set_ylabel("Cards First Answered") return fig
def graph_prices(x, y, gname): '''make a plot of the prices over time for a specific game' x is be the dates of the bins y is the prices gname is the name of the game ''' x_list = list(x) x_dt = [datetime.fromtimestamp(xx) for xx in x_list] fig=Figure(facecolor='white') ax=fig.add_subplot(111) ax.plot(x_dt,y,'r-') ax.set_ylim([0,np.max(y) + np.max(y) * 0.10]) #ax.set_title(gname) #ax.set_axis_bgcolor('red') formatter = FuncFormatter(money_format) ax.yaxis.set_major_formatter(formatter) #fig.autofmt_xdate() #xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S') #ax.xaxis.set_major_formatter(xfmt) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) fig.autofmt_xdate() canvas=FigureCanvas(fig) png_output = StringIO.StringIO() canvas.print_png(png_output) response=make_response(png_output.getvalue()) response.headers['Content-Type'] = 'image/png' return response
class DevPlot(Plot): def __init__(self,k1={'intel_snb' : ['intel_snb','intel_snb','intel_snb']},k2={'intel_snb':['LOAD_1D_ALL','INSTRUCTIONS_RETIRED','LOAD_OPS_ALL']},processes=1,**kwargs): self.k1 = k1 self.k2 = k2 super(DevPlot,self).__init__(processes=processes,**kwargs) def plot(self,jobid,job_data=None): self.setup(jobid,job_data=job_data) cpu_name = self.ts.pmc_type type_name=self.k1[cpu_name][0] events = self.k2[cpu_name] ts=self.ts n_events = len(events) self.fig = Figure(figsize=(8,n_events*2+3),dpi=110) do_rate = True scale = 1.0 if type_name == 'mem': do_rate = False scale=2.0**10 if type_name == 'cpu': scale=ts.wayness*100.0 for i in range(n_events): self.ax = self.fig.add_subplot(n_events,1,i+1) self.plot_lines(self.ax, [i], 3600., yscale=scale, do_rate = do_rate) self.ax.set_ylabel(events[i],size='small') self.ax.set_xlabel("Time (hr)") self.fig.subplots_adjust(hspace=0.5) #self.fig.tight_layout() self.output('devices')
def plot_activity(values): daysFmt = DateFormatter("%d-%B %H:00") fig=Figure() ax=fig.add_subplot(111) times = values.keys() times.sort() number_found = [values[key] for key in times] ax.plot_date(times, number_found, '-') #assert 0, '%s'%(values) # format the ticks ax.xaxis.set_major_locator(HourLocator(byhour=range(0,24,4))) ax.xaxis.set_major_formatter(daysFmt) ax.autoscale_view() ax.grid(True) ax.set_title('All devices') fig.autofmt_xdate() canvas=FigureCanvas(fig) response=HttpResponse(content_type='image/png') canvas.print_png(response) return response
def player_wp(request, code): try: player = Player.objects.get(code=code) except Player.DoesNotExist: raise Http404 points = player.weekly_points.values_list('points', flat=True) response = HttpResponse(content_type='image/png') if points: weeks = list(player.weekly_points.values_list('week', flat=True)) fig = Figure(figsize=(0.4 * min(max(10, weeks[-1]), 22), 3), dpi=100, facecolor='white') ax = fig.add_subplot(111) rects = ax.bar(weeks, points, align='center', linewidth=1, color='#008ad1', width=1) ax.set_xlabel("Week") ax.set_ylabel("Points") ax.set_xticks(weeks) # add a tick for every week for p, rect in zip(points, rects): if p != 0: if p < 0: h = p * 2 - 1 elif p > 0: h = p + 1 ax.text(rect.get_x() + rect.get_width() / 2., h, str(p), fontsize=10, color='black', ha='center') ax.set_xlim((0.5, max(10, weeks[-1]) + 0.5)) else: fig = Figure(figsize=(1, 1), dpi=1, facecolor='white') # return one white pixel canvas = FigureCanvas(fig) canvas.print_png(response) return response
def __init__(self): c = 3.0e+11 # speed of light, um/ms cs = 2.8e-11 # cross section, um^2 n = 1.5 self.WI = (c/n)*cs # 18.0, um^3/ms self.Nv = 5.0e+7 # 5.0e+7 1/um^3 - density of active particles self.W2 = 1./0.23 # 1/ms - 1/spontaneous emission lifetime (2->1 transitions) self.W3 = 1.e-3*self.W2 # 1/ms - 1/spontaneous emission lifetime (3->2 transitions) self.eta = 1.e-16 tb, te, self.ts = 0.0, 1.0, 1.0e-4 self.x = arange(tb,te,self.ts) self.Np = len(self.x) self.y1 = ndarray(shape=(self.Np), dtype='float') self.y2 = ndarray(shape=(self.Np), dtype='float') # self.y3 = ndarray(shape=(self.Np), dtype='float') self.y4 = ndarray(shape=(self.Np), dtype='float') self.PlotWindow = Tk.Toplevel() self.PlotWindow.title('numerical simulation of kinetic equations') fig = Figure(figsize=(10,6), dpi=100) self.g1 = fig.add_subplot(211) self.g2 = fig.add_subplot(212) self.canvas = FigureCanvasTkAgg(fig, self.PlotWindow) self.canvas.show() self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.toolbar = NavigationToolbar2TkAgg( self.canvas, self.PlotWindow) self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
def save(self, name, log=False, vrange=None): if self.imdict['X'].sum() == 0.0 and log: warn("can't plot {}, in log mode".format(name), RuntimeWarning, stacklevel=2) return fig = Figure(figsize=(8,6)) canvas = FigureCanvas(fig) ax = fig.add_subplot(1,1,1) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="1.5%") if log: norm=LogNorm() else: norm=Normalize() if vrange: self.imdict['vmin'], self.imdict['vmax'] = vrange im = ax.imshow(norm=norm,**self.imdict) cb_dict = {'cax':cax} if log: cb_dict['ticks'] = LogLocator(10, np.arange(0.1,1,0.1)) cb_dict['format'] = LogFormatterMathtext(10) try: cb = plt.colorbar(im, **cb_dict) except ValueError: print self.imdict['X'].sum() raise ax.set_xlabel(self.x_label, x=0.98, ha='right') ax.set_ylabel(self.y_label, y=0.98, ha='right') if self.cb_label: cb.set_label(self.cb_label, y=0.98, ha='right') canvas.print_figure(name, bbox_inches='tight')
class TestDialog( QDialog, Ui_dlgMPLTest ): def __init__( self, parent = None ): super( TestDialog, self ).__init__( parent ) self.setupUi( self ) # initialize mpl plot self.figure = Figure() #self.figure.set_figsize_inches( ( 4.3, 4.2 ) ) self.axes = self.figure.add_subplot( 111 ) self.figure.suptitle( "Frequency distribution", fontsize = 12 ) self.axes.grid( True ) self.canvas = FigureCanvas( self.figure ) layout = QVBoxLayout() self.widgetPlot.setLayout(layout) layout.addWidget(self.canvas) #self.canvas.setParent( self.widgetPlot ) # draw mpl plot #self.axes.clear() #self.axes.grid( True ) #self.figure.suptitle( "Frequency distribution", fontsize = 12 ) self.axes.set_ylabel( "Count", fontsize = 8 ) self.axes.set_xlabel( "Values", fontsize = 8 ) x = [ 4, 1, 5, 3, 3, 2, 3, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1 ] n, bins, pathes = self.axes.hist( x, 18, alpha=0.5, histtype = "bar" ) self.canvas.draw() self.setWindowTitle( self.tr( "MPL test" ) )
def plot_sfh(model_sfh, mock_sfh, plot_path): labels = {'lewis': r'ACS-MS', 'oir_all': r'OIR-ALL'} colors = {'lewis': 'dodgerblue', 'oir_all': 'maroon'} fig = Figure(figsize=(3.5, 3.5), frameon=False) canvas = FigureCanvas(fig) gs = gridspec.GridSpec(1, 1, left=0.18, right=0.95, bottom=0.15, top=0.95, wspace=None, hspace=None, width_ratios=None, height_ratios=None) ax = fig.add_subplot(gs[0]) for plane_key in ['lewis', 'oir_all']: if plane_key not in model_sfh['sfh'].keys(): continue plot_single_sfh_line(ax, model_sfh['sfh'][plane_key], label=labels[plane_key], color=colors[plane_key], drawstyle='steps-mid') _plot_mean_age(ax, model_sfh['sfh'][plane_key].attrs['mean_age'], c=colors[plane_key]) # plot_single_sfh_line(ax, model_sfh, label='Model', color='k') # print model_sfh['sfr'] _plot_mock_sfh(ax, mock_sfh, lw=1.5, c='k', label='Mock') _plot_mean_age(ax, mock_sfh.attrs['mean_age']) ax.legend(loc='lower left', fontsize=8, frameon=True) gs.tight_layout(fig, pad=1.08, h_pad=None, w_pad=None, rect=None) canvas.print_figure(plot_path + ".pdf", format="pdf")
def nextDue(self, days=30): self.calcStats() fig = Figure(figsize=(self.width, self.height), dpi=self.dpi) graph = fig.add_subplot(111) dayslists = [self.stats['next'], self.stats['daysByType']['mature']] for dayslist in dayslists: self.addMissing(dayslist, self.stats['lowestInDay'], days) argl = [] for dayslist in dayslists: dl = [x for x in dayslist.items() if x[0] <= days] argl.extend(list(self.unzip(dl))) self.varGraph(graph, days, [dueYoungC, dueMatureC], *argl) cheat = fig.add_subplot(111) b1 = cheat.bar(0, 0, color = dueYoungC) b2 = cheat.bar(1, 0, color = dueMatureC) cheat.legend([b1, b2], [ "Young", "Mature"], loc='upper right') graph.set_xlim(xmin=self.stats['lowestInDay'], xmax=days+1) graph.set_xlabel("Day (0 = today)") graph.set_ylabel("Cards Due") return fig
def simple(request): import random import django import datetime from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.dates import DateFormatter print "hello" #print form['subject'].value() fig=Figure() ax=fig.add_subplot(111) x=[] y=[] now=datetime.datetime.now() delta=datetime.timedelta(days=1) for i in range(10): x.append(now) now+=delta y.append(random.randint(0, 1000)) ax.plot_date(x, y, '-') ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) fig.autofmt_xdate() canvas=FigureCanvas(fig) response=django.http.HttpResponse(content_type='image/png') canvas.print_png(response) return response
def workDone(self, days=30): self.calcStats() for type in ["dayRepsNew", "dayRepsYoung", "dayRepsMature"]: self.addMissing(self.stats[type], -days, 0) fig = Figure(figsize=(self.width, self.height), dpi=self.dpi) graph = fig.add_subplot(111) args = sum((self.unzip(self.stats[type].items(), limit=days, reverseLimit=True) for type in ["dayRepsMature", "dayRepsYoung", "dayRepsNew"][::-1]), []) self.varGraph(graph, days, [reviewNewC, reviewYoungC, reviewMatureC], *args) cheat = fig.add_subplot(111) b1 = cheat.bar(-3, 0, color = reviewNewC) b2 = cheat.bar(-4, 0, color = reviewYoungC) b3 = cheat.bar(-5, 0, color = reviewMatureC) cheat.legend([b1, b2, b3], [ "New", "Young", "Mature"], loc='upper left') graph.set_xlim(xmin=-days+1, xmax=1) graph.set_ylim(ymax=max(max(a for a in args[1::2])) + 10) graph.set_xlabel("Day (0 = today)") graph.set_ylabel("Cards Answered") return fig
def _test_determinism_save(filename, usetex): # This function is mostly copy&paste from "def test_visibility" # To require no GUI, we use Figure and FigureCanvasSVG # instead of plt.figure and fig.savefig from matplotlib.figure import Figure from matplotlib.backends.backend_svg import FigureCanvasSVG from matplotlib import rc rc('svg', hashsalt='asdf') rc('text', usetex=usetex) fig = Figure() ax = fig.add_subplot(111) x = np.linspace(0, 4 * np.pi, 50) y = np.sin(x) yerr = np.ones_like(y) a, b, c = ax.errorbar(x, y, yerr=yerr, fmt='ko') for artist in b: artist.set_visible(False) ax.set_title('A string $1+2+\\sigma$') ax.set_xlabel('A string $1+2+\\sigma$') ax.set_ylabel('A string $1+2+\\sigma$') FigureCanvasSVG(fig).print_svg(filename)
def getImage(self): ddict=self.fitresult try: fig = Figure(figsize=(6,3)) # in inches canvas = FigureCanvas(fig) ax = fig.add_axes([.15, .15, .8, .8]) ax.set_axisbelow(True) logplot = self.plotDict.get('logy', True) if logplot: axplot = ax.semilogy else: axplot = ax.plot axplot(ddict['result']['energy'], ddict['result']['ydata'], 'k', lw=1.5) axplot(ddict['result']['energy'], ddict['result']['continuum'], 'g', lw=1.5) legendlist = ['spectrum', 'continuum', 'fit'] axplot(ddict['result']['energy'], ddict['result']['yfit'], 'r', lw=1.5) fontproperties = FontProperties(size=8) if ddict['result']['config']['fit']['sumflag']: axplot(ddict['result']['energy'], ddict['result']['pileup'] + ddict['result']['continuum'], 'y', lw=1.5) legendlist.append('pileup') if matplotlib_version < '0.99.0': legend = ax.legend(legendlist,0, prop = fontproperties, labelsep=0.02) else: legend = ax.legend(legendlist,0, prop = fontproperties, labelspacing=0.02) except ValueError: fig = Figure(figsize=(6,3)) # in inches canvas = FigureCanvas(fig) ax = fig.add_axes([.15, .15, .8, .8]) ax.set_axisbelow(True) ax.plot(ddict['result']['energy'], ddict['result']['ydata'], 'k', lw=1.5) ax.plot(ddict['result']['energy'], ddict['result']['continuum'], 'g', lw=1.5) legendlist = ['spectrum', 'continuum', 'fit'] ax.plot(ddict['result']['energy'], ddict['result']['yfit'], 'r', lw=1.5) fontproperties = FontProperties(size=8) if ddict['result']['config']['fit']['sumflag']: ax.plot(ddict['result']['energy'], ddict['result']['pileup'] + ddict['result']['continuum'], 'y', lw=1.5) legendlist.append('pileup') if matplotlib_version < '0.99.0': legend = ax.legend(legendlist,0, prop = fontproperties, labelsep=0.02) else: legend = ax.legend(legendlist,0, prop = fontproperties, labelspacing=0.02) ax.set_xlabel('Energy') ax.set_ylabel('Counts') legend.draw_frame(False) outfile = self.outdir+"/"+self.outfile+".png" try: os.remove(outfile) except: pass canvas.print_figure(outfile) return self.__getFitImage(self.outfile+".png")
def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, origin=None): """ Saves a 2D :class:`numpy.array` as an image with one pixel per element. The output formats available depend on the backend being used. Arguments: *fname*: A string containing a path to a filename, or a Python file-like object. If *format* is *None* and *fname* is a string, the output format is deduced from the extension of the filename. *arr*: A 2D array. Keyword arguments: *vmin*/*vmax*: [ None | scalar ] *vmin* and *vmax* set the color scaling for the image by fixing the values that map to the colormap color limits. If either *vmin* or *vmax* is None, that limit is determined from the *arr* min/max value. *cmap*: cmap is a colors.Colormap instance, eg cm.jet. If None, default to the rc image.cmap value. *format*: One of the file extensions supported by the active backend. Most backends support png, pdf, ps, eps and svg. *origin* [ 'upper' | 'lower' ] Indicates where the [0,0] index of the array is in the upper left or lower left corner of the axes. Defaults to the rc image.origin value. """ from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure fig = Figure(figsize=arr.shape[::-1], dpi=1, frameon=False) canvas = FigureCanvas(fig) fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin) fig.savefig(fname, dpi=1, format=format)
def daily_timseries( ts ): fig = Figure( ( 2.56, 2.56 ), 300 ) canvas = FigureCanvas(fig) ax = fig.add_axes((0,0,1,1)) ax.set_ylim( [ 0 , 500 ] ) preferspan = ax.axhspan( SAFE[0], SAFE[1], facecolor='g', alpha=0.2, edgecolor = '#003333', linewidth=1 ) # XXX: gets a list of days. timestamps = glucose.get_days( ts.time ) halfday = dates.relativedelta( hours=12 ) soleday = dates.relativedelta( days=1 ) xmin, xmax = ( timestamps[ 0 ], timestamps[ 1 ] + soleday ) ax.set_xlim( [ xmin, xmax ] ) #fig.autofmt_xdate( ) #plot_glucose_stems( ax, ts ) plt.setp(ax.get_xminorticklabels(), visible=False ) plt.setp(ax.get_xmajorticklabels(), visible=False ) plt.setp(ax.get_ymajorticklabels(), visible=False ) plt.setp(ax.get_yminorticklabels(), visible=False ) ax.grid(True) xmin, xmax = ax.get_xlim( ) log.info( pformat( { 'xlim': [ dates.num2date( xmin ), dates.num2date( xmax ) ], } ) ) return canvas
class Canvas(FigureCanvas): def __init__(self,parent,dpi=100.0): size = parent.size() self.dpi = dpi self.width = size.width() / dpi self.height = size.height() / dpi self.figure = Figure(figsize=(self.width, self.height), dpi=self.dpi, facecolor='w', edgecolor='k', frameon=False) self.figure.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95, wspace=None, hspace=None) self.axes = self.figure.add_subplot(111) self.axes.axis((-1,1,-1,1)) FigureCanvas.__init__(self, self.figure) self.updateGeometry() self.draw() self.cc = self.copy_from_bbox(self.axes.bbox) self.particle_plot = None self.setParent(parent) self.blit(self.axes.bbox) def on_pre_draw(self): self.restore_region(self.cc) def on_draw(self): raise NotImplementedError def on_post_draw(self): self.blit(self.axes.bbox) def redraw(self): self.on_pre_draw() self.on_draw() self.on_post_draw()
class CoffeeCanvas(FigureCanvas): def __init__(self): self.fig = Figure() self.ax = self.fig.add_subplot(1,1,1) super().__init__(self.fig) self.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding) self.fig.canvas.draw() def show_bar_graph(self,data,date): self.ax.clear() data_dict = dict(data) for i, key in enumerate(data_dict): self.ax.bar(i,data_dict[key]) self.ax.set_xticks(np.arange(len(data_dict))+0.4) self.ax.set_xticklabels(list(data_dict.keys())) self.fig.autofmt_xdate() self.ax.set_title("Total Sales for {0}".format(date)) self.ax.set_xlabel("Product") self.ax.set_ylabel("Amount (£)") self.fig.canvas.draw() def show_pie_chart(self,data,date): self.ax.clear() data_dict = dict(data) data = list(data_dict.values()) labels = list(data_dict.keys()) self.ax.pie(data,labels=labels,autopct='%1.1f%%') self.ax.set_title("Percentage Sales for {0}".format(date)) self.fig.canvas.draw()
def plot_frame_displacement(realignment_parameters_file, mean_FD_distribution=None, figsize=(11.7,8.3)): FD_power = calc_frame_dispalcement(realignment_parameters_file) fig = Figure(figsize=figsize) FigureCanvas(fig) if mean_FD_distribution: grid = GridSpec(2, 4) else: grid = GridSpec(1, 4) ax = fig.add_subplot(grid[0,:-1]) ax.plot(FD_power) ax.set_xlim((0, len(FD_power))) ax.set_ylabel("Frame Displacement [mm]") ax.set_xlabel("Frame number") ylim = ax.get_ylim() ax = fig.add_subplot(grid[0,-1]) sns.distplot(FD_power, vertical=True, ax=ax) ax.set_ylim(ylim) if mean_FD_distribution: ax = fig.add_subplot(grid[1,:]) sns.distplot(mean_FD_distribution, ax=ax) ax.set_xlabel("Mean Frame Dispalcement (over all subjects) [mm]") MeanFD = FD_power.mean() label = "MeanFD = %g"%MeanFD plot_vline(MeanFD, label, ax=ax) return fig
def plot(title='title',xlab='x',ylab='y',mode='plot', data={'xxx':[(0,0),(1,1),(1,2),(3,3)], 'yyy':[(0,0,.2,.2),(2,1,0.2,0.2),(2,2,0.2,0.2),(3,3,0.2,0.3)]}): fig=Figure() fig.set_facecolor('white') ax=fig.add_subplot(111) if title: ax.set_title(title) if xlab: ax.set_xlabel(xlab) if ylab: ax.set_ylabel(ylab) legend=[] keys=sorted(data) for key in keys: stream = data[key] (x,y)=([],[]) for point in stream: x.append(point[0]) y.append(point[1]) if mode=='plot': ell=ax.plot(x, y) legend.append((ell,key)) if mode=='hist': ell=ax.hist(y,20) if legend: ax.legend([x for (x,y) in legend], [y for (x,y) in legend], 'upper right', shadow=True) canvas=FigureCanvas(fig) stream=cStringIO.StringIO() canvas.print_png(stream) return stream.getvalue()
def refreshTimeline(self): if not self.firstPlot: self.figureLayout.removeWidget(self.canvas) self.firstPlot = False fig = Figure((2.0, 1.5), dpi=100) self.canvas = FigureCanvas(fig) self.canvas.setParent(self) self.ax = fig.add_subplot(111) self.ax.clear() # levantar el controlDict y ver los tracers Tf = float(self.parsedData["endTime"]) T = float(self.currtime) dT = float(self.parsedData["deltaT"]) self.ax.set_ylim(0, 1.1) self.ax.set_xlim(-10 * dT, Tf) self.ax.plot([0, T - dT, T, T + dT, Tf], [0, 0, 1, 0, 0], "k", marker="o", label="Current Time") i = 0 for itracer in self.tracersData: Tini = float(itracer["startTime"]) if float(itracer["startTime"]) < T: Tini = T self.ax.plot([0, Tini, Tini + dT, Tf], [0, 0, 1, 1], self.colors[i % 6], label=itracer["name"]) i = i + 1 self.ax.set_title("Timeline") self.ax.set_xlabel("Time [s]") self.ax.set_ylabel("Event") self.ax.legend(loc=0, fontsize="small") self.figureLayout.addWidget(self.canvas)
def configure_subplots(self, button): toolfig = Figure(figsize=(6, 3)) canvas = self._get_canvas(toolfig) toolfig.subplots_adjust(top=0.9) tool = SubplotTool(self.canvas.figure, toolfig) w = int(toolfig.bbox.width) h = int(toolfig.bbox.height) window = Gtk.Window() try: window.set_icon_from_file(window_icon) except Exception: # we presumably already logged a message on the # failure of the main plot, don't keep reporting pass window.set_title("Subplot Configuration Tool") window.set_default_size(w, h) vbox = Gtk.Box() vbox.set_property("orientation", Gtk.Orientation.VERTICAL) window.add(vbox) vbox.show() canvas.show() vbox.pack_start(canvas, True, True, 0) window.show()
def simple(): # import datetime # import StringIO #get the polyline map using api: get_activity_map() from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure # from matplotlib.dates import DateFormatter import polyline m = session['map'] summary_lat_lon = polyline.decode(m.summary_polyline) fig=Figure() ax=fig.add_subplot(111) lats = [i[0] for i in summary_lat_lon] lons = [i[1] for i in summary_lat_lon] # x=[] # y=[] # now=datetime.datetime.now() # delta=datetime.timedelta(days=1) # for i in range(10): # x.append(now) # now+=delta # y.append(random.randint(0, 1000)) # ax.plot_date(x, y, '-') # ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) ax.scatter(lons,lats) fig.autofmt_xdate() canvas=FigureCanvas(fig) png_output = StringIO.StringIO() canvas.print_png(png_output) response=make_response(png_output.getvalue()) response.headers['Content-Type'] = 'image/png' return response
def _plot(self, x,y): root = Tk.Tk() root.wm_title("") f = Figure(figsize=(6,6), dpi=100) a = f.add_subplot(111) t = arange(0.0,3.0,0.01) s = sin(2*pi*t) a.plot(t,s) # a tk.DrawingArea canvas = FigureCanvasTkAgg(f, master=root) canvas.show() canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) toolbar = NavigationToolbar2TkAgg( canvas, root ) toolbar.update() canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) def _quit(): root.quit() # stops mainloop root.destroy() # this is necessary on Windows to prevent # Fatal Python Error: PyEval_RestoreThread: NULL tstate button = Tk.Button(master=root, text='Quit', command=_quit) button.pack(side=Tk.BOTTOM) Tk.mainloop() # If you put root.destroy() here, it will cause an error if # the window is closed with the window manager.
def _write_fig(self, plots, fig_label): fig = Figure() ax = fig.add_subplot(111) if self.legend is not None: plotlist = numpy.argsort(self.legend) else: plotlist = xrange(len(plots)) for i in plotlist: if plots[i].shape[0] != 2: raise ValueError, "Attempting to plot matrix with row count other than 2" if self.legend is not None: ax.plot(plots[i][0], plots[i][1], self.colours.next(), label=self.legend[i]) else: ax.plot(plots[i][0], plots[i][1], self.colours.next()) if self.legend is not None: ax.legend(loc='best') canvas = FigureCanvas(fig) canvas.figure.savefig(new_filename(fig_label, 'figure', '.png'))