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
def tiled_axis( ts, filename=None ): fig = Figure( ( 2.56 * 4, 2.56 * 4), 300 ) canvas = FigureCanvas(fig) #ax = fig.add_subplot(111) grid = ImageGrid(fig, 111, # similar to subplot(111) nrows_ncols = (3, 1), axes_pad = 0.5, add_all=True, label_mode = "L", ) # pad half a day so that major ticks show up in the middle, not on the edges delta = dates.relativedelta( days=2, hours=12 ) # XXX: gets a list of days. timestamps = glucose.get_days( ts.time ) xmin, xmax = ( timestamps[ 0 ] - delta, timestamps[ -1 ] + delta ) fig.autofmt_xdate( ) def make_plot( ax, limit ): preferspan = ax.axhspan( SAFE[0], SAFE[1], facecolor='g', alpha=0.2, edgecolor = '#003333', linewidth=1 ) def draw_title( ax, limit ): ax.set_title('glucose history') #ax.set_ylabel('glucose mm/dL') return canvas
def grid( data ): fig = Figure( ( 2.56, 2.56 ), 300 ) canvas = FigureCanvas(fig) d = data.time[ 0 ] day = glucose.glucose_for_day( data, d ) days = glucose.get_days( data.time ) name = str( d ) ax = fig.add_axes((.5,0,1,1)) xmin, xmax = days[ 0 ], days[ -1 ] ax.set_xlim( [ xmin, xmax ] ) ax.grid(True) safe_span(ax) one = ax.text( .50, .50, name, horizontalalignment='center', verticalalignment='center', transform = ax.transAxes ) one.remove( ) log.info( pformat( one ) ) ax.text( .60, .60, name + "two", horizontalalignment='center', verticalalignment='center', transform = ax.transAxes ) set_daily_locators( ax ) config_yaxis( ax ) return canvas
def draw_tile(name): fig = Figure((2.56, 2.56), 300) canvas = FigureCanvas(fig) ax = fig.add_axes((0, 0, 1, 1)) SAFE = (70, 140) 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 = datetime.date.today() halfday = dates.relativedelta(hours=12) soleday = dates.relativedelta(days=1) xmin, xmax = (timestamps, timestamps + 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.text(.50, .50, name, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes) ax.grid(True) fig.savefig(name, transparent=True)
def x_axis_panel(xlim=(0, 1000), numticks=5): fig = Figure((2.56, 2.56), 300) ax = fig.add_axes((0, 0, 1, 1)) ax.grid(True) config_yaxis(ax) config_xaxis(ax, numticks) safe_span(ax) canvas = FigureCanvas(fig) return get_image_buffer(canvas)
def __init__(self, ghgw, hspace=0.35, wspace=0.2, rwidth=3.0, rheight=2.8): self.gh = ghgw[0] self.gw = ghgw[1] # Setup the figure looking nice self.fig = matplotlib.figure.Figure( figsize=(rwidth * self.gw, rheight * self.gh), subplotpars=matplotlib.figure.SubplotParams(hspace=hspace, wspace=wspace)) self.canvas = FigureCanvas(self.fig)
def debug(msg): fig = Figure((2.56, 2.56), 300, linewidth=.5) canvas = FigureCanvas(fig) ax = fig.add_axes((0, 0, 1, 1)) config_yaxis(ax, formatter=False) config_xaxis(ax, 5) ax.grid(True) ax.text(0, 1, msg, verticalalignment='top', transform=ax.transAxes) return get_image_buffer(canvas)
def dot(color='r'): fig = Figure((.12, .12), 300) canvas = FigureCanvas(fig) ax = fig.add_axes((0, 0, 1, 1), frameon=False) ax.set_ylim([0, 1]) ax.set_xlim([0, 1]) ax.plot(.5, .5, 'ro') ax.grid(False) ax.tick_params('both', width=0, length=0) return get_image_buffer(canvas)
def giant_timeseries(ts): fig = Figure((20.3, 3.5), 300) canvas = FigureCanvas(fig) ax = fig.add_subplot(111) preferspan = ax.axhspan(SAFE[0], SAFE[1], facecolor='g', alpha=0.35, edgecolor='#003333', linewidth=1) # visualize glucose using stems # XXX: gets a list of days. timestamps = glucose.get_days(ts.time) delta = dates.relativedelta(days=1, hours=12) oneday = dates.relativedelta(days=1) xmin, xmax = (timestamps[0], timestamps[-1]) ax.set_xlim([xmin, xmax]) markers, stems, baselines = ax.stem(ts.time, ts.value, linefmt='b:') plt.setp(markers, color='red', linewidth=.5, marker='o') plt.setp(baselines, marker='None') fig.autofmt_xdate() ax.set_title('glucose history') ax.grid(True) ax.set_xlabel('time') majorLocator = dates.DayLocator() majorFormatter = dates.AutoDateFormatter(majorLocator) minorLocator = dates.HourLocator(interval=6) minorFormatter = dates.AutoDateFormatter(minorLocator) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) ax.xaxis.set_minor_locator(minorLocator) ax.xaxis.set_minor_formatter(minorFormatter) labels = ax.get_xminorticklabels() plt.setp(labels, rotation=30, fontsize='small') plt.setp(ax.get_xmajorticklabels(), rotation=30, fontsize='medium') xmin, xmax = ax.get_xlim() log.info(pformat({ 'xlim': [dates.num2date(xmin), dates.num2date(xmax)], })) ax.set_ylabel('glucose mm/dL') return canvas
def y_axis_panel( ): """Just get the yaxis""" """TODO: more sensitive ticks?""" fig = Figure( ( .64, 5.12 ), 300 ) canvas = FigureCanvas(fig) ax = fig.add_axes((.9,1./3.,1.,.5)) ax.grid(True) config_yaxis( ax ) safe_span(ax) ax.xaxis.set_visible(False) return canvas
def y_axis_panel(size=(.64, 3.84)): """Just get the yaxis""" """TODO: more sensitive ticks?""" fig = Figure(size, 300) canvas = FigureCanvas(fig) ax = fig.add_axes((.9, 1 / 6., 1., 2 / 3.0)) ax.grid(True) config_yaxis(ax) safe_span(ax) ax.xaxis.set_visible(False) return get_image_buffer(canvas)
def jpg(self): """ Returns a StringIO JPG plot for the sensor """ fig = self.matplot() canvas = FigureCanvas(fig) try: jpg_output = StringIO() except NameError: jpg_output = BytesIO() canvas.print_jpg(jpg_output) return jpg_output.getvalue()
def exp( data ): fig = Figure( ( 2.56, 2.56 ), 300 ) canvas = FigureCanvas(fig) d = data.time[ 0 ] day = glucose.glucose_for_day( data, d ) name = str( d ) ax = fig.add_axes((0,0,1,1)) ax.text( .50, .50, name, horizontalalignment='center', verticalalignment='center', transform = ax.transAxes ) ax.grid(True) return canvas
def png(self): """ Returns a StringIO PNG plot for the sensor """ fig = self.matplot() canvas = FigureCanvas(fig) try: png_output = StringIO() except NameError: png_output = BytesIO() canvas.print_png(png_output) return png_output.getvalue()
def daily_axis( ts ): # http://matplotlib.sourceforge.net/mpl_toolkits/axes_grid/users/overview.html fig = Figure( ( 2.56, 2.56 ), 300 ) canvas = FigureCanvas(fig) ax = fig.add_subplot(111) safe_span(ax) timestamps = glucose.get_days( ts.time ) xmin, xmax = timestamps[ 0 ], timestamps[ -1 ] ax.set_xlim( [ xmin, xmax ] ) ax.set_ylim( [ ts.value.min( ) *.85 , 600 ] ) log.info( pformat( timestamps ) ) #fig.autofmt_xdate( ) ax.grid(True) return canvas
def plot_data_split(request, id, split_nr): split_nr = int(split_nr) task = get_object_or_404(Task, pk=id) img = [task.get_split_image(split_nr)] #import pdb #pdb.set_trace() if (img == None): return None # why it does not work ? from pylab import axis axis('off') from StringIO import StringIO dpi = 60 bgcol = '#ffffff' fig = Figure(figsize=(7, 0.3), dpi=dpi, facecolor=bgcol) canvas = FigureCanvas(fig) bx = fig.add_subplot(111) bx.set_yticklabels([]) bx.set_xticklabels([]) bx.set_yticks([]) #import pdb #pdb.set_trace() bx.imshow(img, aspect='auto', interpolation='nearest', vmin=0, vmax=3, cmap=cmap_mldata) # bx = fig.add_subplot(212) # bx.set_yticklabels([]) # bx.set_xticklabels([]) # bx.imshow(img,aspect='auto',interpolation='nearest',cmap=cm.jet,extent=[0,len(img[0])-1,0,1]) canvas.draw() imdata = StringIO() fig.savefig(imdata, format='png', dpi=dpi, facecolor=bgcol) return HttpResponse(imdata.getvalue(), mimetype='image/png')
def daily_axis(ts): # http://matplotlib.sourceforge.net/mpl_toolkits/axes_grid/users/overview.html fig = Figure((2.56, 2.56), 300) canvas = FigureCanvas(fig) ax = fig.add_subplot(111) preferspan = ax.axhspan(SAFE[0], SAFE[1], facecolor='g', alpha=0.2, edgecolor='#003333', linewidth=1) timestamps = glucose.get_days(ts.time) xmin, xmax = timestamps[0], timestamps[-1] ax.set_xlim([xmin, xmax]) ax.set_ylim([ts.value.min() * .85, 600]) log.info(pformat(timestamps)) #fig.autofmt_xdate( ) ax.grid(True) return canvas
def stats_helper(request, software_id, type, dpi): # matplotlib needs a writable home directory if settings.PRODUCTION: import os os.environ['HOME']='/home/mloss/tmp' import matplotlib import datetime matplotlib.use('Cairo') from matplotlib.figure import Figure from matplotlib.backends.backend_cairo import FigureCanvasCairo as FigureCanvas from matplotlib.dates import DayLocator, WeekdayLocator, HourLocator, MonthLocator, YearLocator from matplotlib.dates import DateFormatter, date2num from StringIO import StringIO if dpi<=40: bgcol='#f7f7f7' else: bgcol='#ffffff' fig = Figure(figsize=(8,6), dpi=dpi, facecolor=bgcol) canvas = FigureCanvas(fig) ax = fig.add_subplot(111) stat = SoftwareStatistics.objects.filter(software=software_id).distinct().order_by('date') if stat.count()<=0: return HttpResponseForbidden() x=list() y=list() for entry in stat: x.append(date2num(entry.date)) if type=='downloads': y.append(entry.number_of_downloads) elif type=='views': y.append(entry.number_of_views) #ax.plot(x,y,'bo', alpha=0.7) #ax.plot(x,y,'b-',linewidth=1, alpha=0.5) ax.bar(x,y) days = DayLocator() weeks= WeekdayLocator() months= MonthLocator() years= YearLocator() dateFmt = DateFormatter("%Y-%m-%d") ax.xaxis.set_major_formatter(dateFmt) if len(x)<=14: ax.xaxis.set_major_locator(days) elif len(x)<60: ax.xaxis.set_major_locator(weeks) ax.xaxis.set_minor_locator(days) elif len(x)<720: ax.xaxis.set_major_locator(months) ax.xaxis.set_minor_locator(weeks) else: ax.xaxis.set_major_locator(years) ax.xaxis.set_minor_locator(months) if dpi>40: if type=='downloads': ax.set_title('Number of Downloads') ax.set_ylabel('Downloads per Day') elif type=='views': ax.set_title('Number of Views') ax.set_ylabel('Views per Day') ax.grid(True) ax.axis("tight") for label in ax.get_xticklabels(): label.set_ha('right') label.set_rotation(30) canvas.draw() imdata=StringIO() fig.savefig(imdata,format='png', dpi=dpi, facecolor=bgcol) del fig del ax return HttpResponse(imdata.getvalue(), mimetype='image/png')
def plot_legend(request): import numpy img = numpy.array([[0, 1, 2, 3]]) #from pylab import axis #axis('off') from StringIO import StringIO dpi = 25 bgcol = '#ffffff' fig = Figure(figsize=(7, 1.5), dpi=dpi, facecolor=bgcol) canvas = FigureCanvas(fig) ax = fig.add_subplot(171) ax.set_title('not used') ax.title.set_fontsize(30) ax.set_yticklabels([]) ax.set_xticklabels([]) ax.set_yticks([]) ax.set_xticks([]) ax.imshow([[0]], interpolation='nearest', vmin=0, vmax=3, cmap=cmap_mldata) bx = fig.add_subplot(173) bx.set_title('train') bx.title.set_fontsize(30) bx.set_yticklabels([]) bx.set_xticklabels([]) bx.set_yticks([]) bx.set_xticks([]) bx.imshow([[1]], interpolation='nearest', vmin=0, vmax=3, cmap=cmap_mldata) cx = fig.add_subplot(175) cx.set_title('validation') cx.title.set_fontsize(30) cx.set_yticklabels([]) cx.set_xticklabels([]) cx.set_yticks([]) cx.set_xticks([]) cx.imshow([[2]], interpolation='nearest', vmin=0, vmax=3, cmap=cmap_mldata) dx = fig.add_subplot(177) dx.set_title('test') dx.title.set_fontsize(30) dx.set_yticklabels([]) dx.set_xticklabels([]) dx.set_yticks([]) dx.set_xticks([]) dx.imshow([[3]], interpolation='nearest', vmin=0, vmax=3, cmap=cmap_mldata) #bx.set_title('legend') #bx.set_yticklabels([]) #bx.set_xticklabels([]) #bx.set_yticklabels([]) #bx.set_xticklabels(['not used','train','validation','test']) #bx.set_yticks([]) #bx.set_xticks([2,7,12,17]) #for label in bx.get_xticklabels(): # label.set_fontsize(12) #bx.imshow([[0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3]],aspect=None,interpolation='nearest',cmap=cm.Greys) canvas.draw() imdata = StringIO() fig.savefig(imdata, format='png', dpi=dpi, facecolor=bgcol) return HttpResponse(imdata.getvalue(), mimetype='image/png')
signal= cplx_randn(SIGLEN) sc_half_seq= cplx_randn(SCLEN) sc_seq= np.concatenate((sc_half_seq[-CPLEN:], sc_half_seq, sc_half_seq)) start= (len(signal) - len(sc_seq)) // 2 end= start + len(sc_seq) signal[start:end]+= sc_seq for (fqname, fqoff) in (('nooff', 0), ('fqoff', 0.01)): df= np.exp(1j * np.linspace(0, fqoff * SIGLEN, len(signal))) fqadj= signal * df detection= fqadj[SCLEN:] * fqadj[:-SCLEN].conj() detection= np.convolve(detection, np.ones(SCLEN) / SCLEN, mode='valid') for (name, src) in (('abs', abs(detection)), ('arg', np.angle(detection))): fig= Figure() canvas= FigureCanvas(fig) ax= fig.add_subplot('111') sl= len(src) ax.plot( np.linspace(-sl/2, sl/2, sl), src, 'b' ) canvas.print_pdf('sc_detector_output_{}_{}.pdf'.format(fqname, name))
def tiled_axis(ts, filename=None): fig = Figure((2.56 * 4, 2.56 * 4), 300) canvas = FigureCanvas(fig) #ax = fig.add_subplot(111) grid = ImageGrid( fig, 111, # similar to subplot(111) nrows_ncols=(3, 1), axes_pad=0.5, add_all=True, label_mode="L", ) # pad half a day so that major ticks show up in the middle, not on the edges delta = dates.relativedelta(days=2, hours=12) # XXX: gets a list of days. timestamps = glucose.get_days(ts.time) xmin, xmax = (timestamps[0] - delta, timestamps[-1] + delta) fig.autofmt_xdate() def make_plot(ax, limit): preferspan = ax.axhspan(SAFE[0], SAFE[1], facecolor='g', alpha=0.2, edgecolor='#003333', linewidth=1) def draw_glucose(ax, limit): xmin, xmax = limit # visualize glucose using stems ax.set_xlim([xmin, xmax]) markers, stems, baselines = ax.stem(ts.time, ts.value, linefmt='b:') plt.setp(markers, color='red', linewidth=.5, marker='o') plt.setp(baselines, marker='None') def draw_title(ax, limit): ax.set_title('glucose history') def get_axis(ax, limit): xmin, xmax = limit ax.set_xlim([xmin, xmax]) ax.grid(True) #ax.set_ylim( [ ts.value.min( ) *.85 , 600 ] ) #ax.set_xlabel('time') majorLocator = dates.DayLocator() majorFormatter = dates.AutoDateFormatter(majorLocator) minorLocator = dates.HourLocator(interval=6) minorFormatter = dates.AutoDateFormatter(minorLocator) #ax.xaxis.set_major_locator(majorLocator) #ax.xaxis.set_major_formatter(majorFormatter) ax.xaxis.set_minor_locator(minorLocator) ax.xaxis.set_minor_formatter(minorFormatter) labels = ax.get_xminorticklabels() plt.setp(labels, rotation=30, fontsize='small') plt.setp(ax.get_xmajorticklabels(), rotation=30, fontsize='medium') xmin, xmax = ax.get_xlim() log.info( pformat({ 'xlim': [dates.num2date(xmin), dates.num2date(xmax)], 'xticks': dates.num2date(ax.get_xticks()), })) for i, day in enumerate(timestamps): ax = grid[i] get_axis(ax, [day, day + delta]) name = '%s-%d.png' % (day.isoformat(), i) #fig.savefig( name ) canvas.print_figure(name) # fig.clf() #make_plot( ax, #ax.set_ylabel('glucose mm/dL') return canvas
def x_axis_panel( ): fig = Figure( ( 2.56, 2.56 ), 300 ) canvas = FigureCanvas(fig)