Ejemplo n.º 1
0
	def update(self):
		if isinstance(self.line,matplotlib.image.AxesImage):
			# image name
			try:
				if len(self.xdata)==0 and self.dataName: self.xdata=self.imgData[self.dataName]  # empty list reference an empty singleton, not the list we want; adjust here
				import Image
				if self.xdata[current]==None: img=Image.new('RGBA',(1,1),(0,0,0,0))
				else: img=Image.open(self.xdata[current])
				self.line.set_data(img)
			except IndexError: pass
		else:
			# regular data
			import numpy
			# current==-1 avoids copy slicing data in the else part
			if current==None or current==-1 or afterCurrentAlpha==1:
				self.line.set_xdata(self.xdata); self.line.set_ydata(self.ydata)
				self.line2.set_xdata([]); self.line2.set_ydata([])
			else:
				try: # try if we can extend the first part by one so that lines are connected
					self.xdata[:current+1]; preCurrEnd=current+1
				except IndexError: preCurrEnd=current
				preCurrEnd=current+(1 if len(self.xdata)>current else 0)
				self.line.set_xdata(self.xdata[:preCurrEnd]); self.line.set_ydata(self.ydata[:preCurrEnd])
				self.line2.set_xdata(self.xdata[current:]); self.line2.set_ydata(self.ydata[current:])
			try:
				x,y=self.xdata[current],self.ydata[current]
			except IndexError: x,y=0,0
			# this could be written in a nicer way, very likely
			try:
				pt=numpy.ndarray((2,),buffer=numpy.array([float(x),float(y)]))
				if self.scatter:
					self.scatter.set_offsets(pt)
					# change rotation of the marker (possibly incorrect)
					try:
						dx,dy=self.xdata[current]-self.xdata[current-1],self.ydata[current]-self.ydata[current-1]
						# smoothing from last n values, if possible
						# FIXME: does not show arrow at all if less than window values
						#try:
						#	window=10
						#	dx,dy=[numpy.average(numpy.diff(dta[current-window:current])) for dta in self.xdata,self.ydata]
						#except IndexError: pass
						# there must be an easier way to find on-screen derivative angle, ask on the matplotlib mailing list
						axes=self.line.get_axes()
						p=axes.patch; xx,yy=p.get_verts()[:,0],p.get_verts()[:,1]; size=max(xx)-min(xx),max(yy)-min(yy)
						aspect=(size[1]/size[0])*(1./axes.get_data_ratio())
						angle=math.atan(aspect*dy/dx)
						if dx<0: angle-=math.pi
						self.scatter.set_transform(matplotlib.transforms.Affine2D().rotate(angle))
					except IndexError: pass
				if self.annotation:
					if math.isnan(x) or math.isnan(y):
						if hasattr(self.annotation,'xyann'): self.annotation.xyann=(x,y)
						else: self.annotation.xytext=(0,0)
						self.annotation.set_text('') # make invisible, place anywhere
					else:
						#
						if hasattr(self.annotation,'xyann'): self.annotation.xyann=(x,y) # newer MPL versions (>=1.4)
						else: self.annotation.xyann=(x,y)
						self.annotation.set_text(self.annotation.annotateFmt.format(xy=(float(x),float(y))))
			except TypeError: pass # this happens at i386 with empty data, saying TypeError: buffer is too small for requested array
def CreerImage(IMA, nom):  # IMA est un tableau de dimensions H*L*3.
    H, L = len(IMA), len(IMA[0])
    im = Image.new('RGB', (L, H))
    pix = im.load()
    for i in range(L):
        for j in range(H):
            pix[i, j] = tuple(IMA[j, i])
    im.save(nom)
Ejemplo n.º 3
0
def imgSizeChanger(size, file_name, new_file_name):
    new_img = Image.new("RGB", size, "white")
    im = Image.open(file_name)
    im.thumbnail(size, Image.ANTIALIAS)
    load_img = im.load()
    load_newimg = new_img.load()
    i_offset = (size - im.size[0]) / 2
    j_offset = (size - im.size[1]) / 2
    for i in range(0, im.size[0]):
        for j in range(0, im.size[1]):
            load_newimg[i + i_offset, j + j_offset] = load_img[i, j]
    new_img.save(new_file_name, "JPEG")
Ejemplo n.º 4
0
def register(request):
    # pass
    if request.method == "POST":
        user_name = request.POST.get('username', '')
        pass_word_1 = request.POST.get('password_1', '')
        pass_word_2 = request.POST.get('password_2', '')
        nick_name = request.POST.get('nickname', '')
        email = request.POST.get('email', '')
        avatar = request.FILES.get('avatar')
        if User.objects.filter(username=user_name):
            return render(request, 'blog/register.html', {'error': '用户已存在'})
        if (pass_word_1 != pass_word_2):
            return render(request, 'blog/register.html', {'error': '两次密码输入不一致'})
        user = User()

        # 将头像设置为圆形
        if avatar:
            user.avatar = 'media/' + user_name + '.png'
            img = Image.open(avatar)
            size = img.size
            r2 = min(size[0], size(1))
            if size[0] != size[1]:
                img = img.resize((r2, r2), Image.ANTIALIAS)
            r3 = int(r2 / 2)
            img_circle = Image.new('RGBA', (r3 * 2, r3 * 2), (255, 255, 255, 0))
            pima = img.load()
            pimb = img_circle.load()
            r = float(r2 / 2)
            for i in range(r2):
                for j in range(r2):
                    lx = abs(i - r)
                    ly = abs(j - r)
                    l = (pow(lx, 2) + pow(ly, 2)) ** 0.5
                    if l < r3:
                        pimb[i - (r - r3), j - (r - r3)] = pima[i, j]
            img_circle.save('static/media/' + user_name + '.png')
        user.username = user_name
        user.password = pass_word_1
        user.email = email
        user.nickname = nick_name
        user.save()
        return render(request, 'blog/index_unlogin.html')
    else:
        return render(request, 'blog/register.html')
Ejemplo n.º 5
0
    def print_to_file(self):
        img = Image.new('RGBA', (W, H), DEFAULT_BACKGROUND_COLOR)
        canvas = aggdraw.Draw(img)

        if (isinstance(self, Curve)):
            self.draw(canvas)
        elif hasattr(self, 'elements'):
            for element in self.elements:
                element.draw(canvas)
        else:
            pass

        canvas.flush()

        image_subdirectory = create_image_subdirectory()
        run_subdirectory = create_run_subdirectory(image_subdirectory)
        file_path = run_subdirectory + '/' + self.__class__.__name__ + '-' + str(
            hash(self)) + '-image.png'
        img.save(file_path)

        os.system(' '.join(['open -a preview', file_path]))
Ejemplo n.º 6
0
def createPlots(P,subPlots=True,noShow=False,replace=True,scatterSize=60,wider=False):
	'''Create plots based on current data;

	:param subPlots: show all plots in one figure as subplots; otherwise, create multiple figures
	:param noShow: use headless backend for plots, and do not show plots on the screen
	:param replace: do not close existing figures, and do not update P.currLineRefs
	'''
	import logging
	data,imgData,plots,labels,xylabels,legendLoc,axesWd,annotateFmt=P.data,P.imgData,P.plots,P.labels,P.xylabels,P.legendLoc,P.axesWd,P.annotateFmt
	if replace:
		if P.currLineRefs:
			logging.info('Closing existing figures')
			ff=set([l.line.get_axes().get_figure() for l in P.currLineRefs]) # get all current figures
			for f in ff: pylab.close(f) # close those
		P.currLineRefs=[]
	figs=[]
	if len(plots)==0: return # nothing to plot
	if subPlots:
		# compute number of rows and colums for plots we have
		subCols=int(round(math.sqrt(len(plots)))); subRows=int(math.ceil(len(plots)*1./subCols))
		if wider: subRows,subCols=subCols,subRows
	# create a new figure; called once with subPlots, for each subplot without subPlots
	def _newFig():
		## pylab API		
		if not noShow: return pylab.figure() # this will go onto the screen; the pylab call sets up the windows as well
		else: # with noShow
			fig=matplotlib.figure.Figure()
			canvas=_HeadlessFigureCanvas(fig) # 
			return fig
	if subPlots: figs=[_newFig()]
	for nPlot,p in enumerate(plots.keys()):
		pStrip=p.strip().split('=',1)[0]
		if not subPlots:
			figs.append(_newFig())
			axes=figs[-1].add_subplot(1,1,1)
		else: axes=figs[-1].add_subplot(subRows,subCols,nPlot+1) # nPlot is 1-based in mpl, for matlab comatibility
		axes.grid(True)
		if plots[p]==None: # image plot
			if not pStrip in imgData.keys(): imgData[pStrip]=[]
			# fake (empty) image if no data yet
			import Image
			if len(imgData[pStrip])==0 or imgData[pStrip][-1]==None: img=Image.new('RGBA',(1,1),(0,0,0,0))
			else: img=Image.open(imgData[pStrip][-1])
			img=axes.imshow(img,origin='upper')
			if replace: P.currLineRefs.append(LineRef(line=img,scatter=None,annotation=None,line2=None,xdata=imgData[pStrip],ydata=None,imgData=imgData,dataName=pStrip))
			axes.set_axis_off()
			continue
		plots_p=[addPointTypeSpecifier(o) for o in tuplifyYAxis(plots[p])]
		plots_p_y1,plots_p_y2=[],[]; y1=True
		missing=set() # missing data columns
		if pStrip not in data.keys(): missing.add(pStrip.decode('utf-8','ignore'))
		for d in plots_p:
			if d[0]==None:
				y1=False; continue
			if not isinstance(d[0],(str,unicode)): raise ValueError('Plots specifiers must be strings (not %s)'%(type(d[0]).__name__))
			if y1: plots_p_y1.append(d)
			else: plots_p_y2.append(d)
			try:
				if (
					d[0] not in data.keys()
					# and not callable(d[0])
					and not (isinstance(d[0],(str,unicode)) and (d[0].startswith('**') or d[0].startswith('*'))) # hack for callable as strings
					# and not hasattr(d[0],'keys')
				):
					missing.add(d[0])
			except UnicodeEncodeError:
				import warnings
				warnings.error('UnicodeDecodeError when processing data set '+repr(d[0]))
		if missing:
			if len(data.keys())==0 or len(data[data.keys()[0]])==0: # no data at all yet, do not add garbage NaNs
				for m in missing: data[m]=[]
			else:
				addDataColumns(data,missing)
				try:
					print 'Missing columns in Scene.plot.data, added NaNs:',', '.join([m.encode('utf-8') for m in missing])
				except UnicodeDecodeError:
					warnings.warn('UnicodeDecodeError reporting missing data columns -- harmless, just wondering...')
		def createLines(pStrip,ySpecs,axes,isY1=True,y2Exists=False):
			'''Create data lines from specifications; this code is common for y1 and y2 axes;
			it handles y-data specified as callables/dicts passed as string (starting with '*'/'**'), which might create additional lines when updated with liveUpdate.
			'''
			# save the original specifications; they will be smuggled into the axes object
			# the live updated will run yNameFuncs to see if there are new lines to be added
			# and will add them if necessary
			yNameFuncs=set()
			yNames=set()
			ySpecs2=[]
			for ys in ySpecs:
				if not isinstance(ys[0],(str,unicode)): raise ValueError('Plot specifications must be strings (not a %s).'%type(ys[0]))
				if ys[0].startswith('**') or ys[0].startswith('*'):
					evEx=eval(ys[0][(2 if ys[0].startswith('**') else 1):],{'S':P.scene})
					yNameFuncs.add(evEx)  # add callable or dictionary
					# XXX: what is ys[1]? Previously, there was no line specifier there for dicts at least
					# print evEx,type(evEx), evEx.__iter__(),type(evEx.__iter__())
					ySpecs2+=[(ret,ys[1]) for ret in evEx] # traverse list or dict keys
				else: ySpecs2.append(ys)
			if len(ySpecs2)==0:
				print 'woo.plot: creating fake plot, since there are no y-data yet'
				line,=axes.plot([nan],[nan])
				line2,=axes.plot([nan],[nan])
				if replace: P.currLineRefs.append(LineRef(line=line,scatter=None,annotation=None,line2=line2,xdata=[nan],ydata=[nan]))
			# set different color series for y1 and y2 so that they are recognizable
			if matplotlib.rcParams.has_key('axes.color_cycle'): matplotlib.rcParams['axes.color_cycle']='b,g,r,c,m,y,k' if not isY1 else 'm,y,k,b,g,r,c'
			for d in ySpecs2:
				yNames.add(d)
				# should have been handled above already
				#if pStrip not in data:
				#	print 'Missing column %s in Scene.plot.data, added NaN.'%pString
				#	addDataColumns(data,[pStrip])
				if d[0] not in data:
					print 'Missing column %s in Scene.plot.data, added NaN.'%d[0]
					addDataColumns(data,[d[0]])
				line,=axes.plot(data[pStrip],data[d[0]],d[1],label=xlateLabel(d[0],P.labels),**lineKw)
				lineKwWithoutAlpha=dict([(k,v) for k,v in lineKw.items() if k!='alpha'])
				line2,=axes.plot([],[],d[1],color=line.get_color(),alpha=afterCurrentAlpha,**lineKwWithoutAlpha)
				# use (0,0) if there are no data yet
				scatterPt=[0,0] if len(data[pStrip])==0 else (data[pStrip][current],data[d[0]][current])
				scatterPtPos=[scatterPt[0] if not math.isnan(scatterPt[0]) else 0,scatterPt[1] if not math.isnan(scatterPt[1]) else 0]
				# if current value is NaN, use zero instead
				scatter=axes.scatter(scatterPtPos[0],scatterPtPos[1],s=scatterSize,color=line.get_color(),**scatterMarkerKw)
				if annotateFmt:
					if math.isnan(scatterPtPos[0]) or math.isnan(scatterPtPos[1]): text=''
					else: text=annotateFmt.format(xy=scatterPt)
					annotation=axes.annotate(text,xy=scatterPtPos,color=line.get_color(),**annotateKw)
					annotation.annotateFmt=annotateFmt
				else: annotation=None
				if replace: P.currLineRefs.append(LineRef(line=line,scatter=scatter,annotation=annotation,line2=line2,xdata=data[pStrip],ydata=data[d[0]]))
			axes=line.get_axes()
			labelLoc=(legendLoc[0 if isY1 else 1] if y2Exists>0 else 'best')
			l=axes.legend(loc=labelLoc)
			if l:
				l.get_frame().set_alpha(legendAlpha)
				if hasattr(l,'draggable'): l.draggable(True)
			if scientific:
				axes.ticklabel_format(style='sci',scilimits=(0,0),axis='both')
				# fixes scientific exponent placement for y2: https://sourceforge.net/mailarchive/forum.php?thread_name=20101223174750.GD28779%40ykcyc&forum_name=matplotlib-users
				if not isY1: axes.yaxis.set_offset_position('right')
			if isY1:
				axes.set_ylabel((', '.join([xlateLabel(_p[0],P.labels) for _p in ySpecs2])) if p not in xylabels or not xylabels[p][1] else xylabels[p][1])
				axes.set_xlabel(xlateLabel(pStrip,P.labels) if (p not in xylabels or not xylabels[p][0]) else xylabels[p][0])
			else:
				axes.set_ylabel((', '.join([xlateLabel(_p[0],P.labels) for _p in ySpecs2])) if (p not in xylabels or len(xylabels[p])<3 or not xylabels[p][2]) else xylabels[p][2])
			# if there are callable/dict ySpecs, save them inside the axes object, so that the live updater can use those
			if yNameFuncs:
				axes.wooYNames,axes.wooYFuncs,axes.wooXName,axes.wooLabelLoc=yNames,yNameFuncs,pStrip,labelLoc # prepend woo to avoid clashes
			if 0:
				# fix missing 'show' method; this has been fixed in matplotlib already, but we need to backport that
				# see https://github.com/matplotlib/matplotlib/commit/15fd0ae587a57cb1d7b69546eb359085315148c8
				# don't do that for headless backend, error there is fine
				fig=axes.get_figure()
				if not hasattr(fig,'show'):
					mgr=getattr(fig.canvas,'manager')
					if mgr: fig.show=lambda *args: mgr.window.show()
		createLines(pStrip,plots_p_y1,axes=axes,isY1=True,y2Exists=len(plots_p_y2)>0)
		if axesWd>0:
			axes.axhline(linewidth=axesWd,color='k')
			axes.axvline(linewidth=axesWd,color='k')
		# create y2 lines, if any
		if len(plots_p_y2)>0:
			axes=axes.twinx() # create the y2 axis
			createLines(pStrip,plots_p_y2,axes,isY1=False,y2Exists=True)
		### scene is not directly accessible from here, do it like this:
		S=woo.master.scene
		if S.plot==P:
			if 'title' in S.tags: axes.set_title(S.tags['title'])
	return figs
Ejemplo n.º 7
0
def createPlots(P,subPlots=True,noShow=False,replace=True,scatterSize=60,wider=False):
    '''Create plots based on current data;

    :param subPlots: show all plots in one figure as subplots; otherwise, create multiple figures
    :param noShow: use headless backend for plots, and do not show plots on the screen
    :param replace: do not close existing figures, and do not update P.currLineRefs
    '''
    import logging
    data,imgData,plots,labels,xylabels,legendLoc,axesWd,annotateFmt=P.data,P.imgData,P.plots,P.labels,P.xylabels,P.legendLoc,P.axesWd,P.annotateFmt
    if replace:
        if P.currLineRefs:
            logging.info('Closing existing figures')
            ff=set([_my_get_axes(l.line).get_figure() for l in P.currLineRefs]) # get all current figures
            for f in ff: pylab.close(f) # close those
        P.currLineRefs=[]
    figs=[]
    if len(plots)==0: return # nothing to plot
    if subPlots:
        # compute number of rows and colums for plots we have
        subCols=int(round(math.sqrt(len(plots)))); subRows=int(math.ceil(len(plots)*1./subCols))
        if wider: subRows,subCols=subCols,subRows
    # create a new figure; called once with subPlots, for each subplot without subPlots
    def _newFig():
        ## pylab API        
        if not noShow: return pylab.figure() # this will go onto the screen; the pylab call sets up the windows as well
        else: # with noShow
            fig=matplotlib.figure.Figure()
            canvas=_HeadlessFigureCanvas(fig) # 
            return fig
    if subPlots: figs=[_newFig()]
    for nPlot,p in enumerate(plots.keys()):
        pStrip=p.strip().split('=',1)[0]
        if not subPlots:
            figs.append(_newFig())
            axes=figs[-1].add_subplot(1,1,1)
        else: axes=figs[-1].add_subplot(subRows,subCols,nPlot+1) # nPlot is 1-based in mpl, for matlab comatibility
        axes.grid(True)
        if plots[p]==None: # image plot
            if not pStrip in list(imgData.keys()): imgData[pStrip]=[]
            # fake (empty) image if no data yet
            import Image
            if len(imgData[pStrip])==0 or imgData[pStrip][-1]==None: img=Image.new('RGBA',(1,1),(0,0,0,0))
            else: img=Image.open(imgData[pStrip][-1])
            img=axes.imshow(img,origin='upper')
            if replace: P.currLineRefs.append(LineRef(line=img,scatter=None,annotation=None,line2=None,xdata=imgData[pStrip],ydata=None,imgData=imgData,dataName=pStrip))
            axes.set_axis_off()
            continue
        plots_p=[addPointTypeSpecifier(o) for o in tuplifyYAxis(plots[p])]
        plots_p_y1,plots_p_y2=[],[]; y1=True
        missing=set() # missing data columns
        if pStrip not in list(data.keys()): missing.add(pStrip if isinstance(pStrip,str) else pStrip.decode('utf-8','ignore'))
        for d in plots_p:
            d0=d[0]
            if d0==None:
                y1=False; continue
            if not isinstance(d0,(past.builtins.str,str)): raise ValueError('Plots specifiers must be strings (not %s)'%(type(d[0]).__name__))
            if '=' in d0: d0=d0.split('=',1)[0]
            if y1: plots_p_y1.append((d0,d[1]))
            else: plots_p_y2.append((d0,d[1]))
            try:
                if (
                    d0 not in list(data.keys())
                    # and not callable(d[0])
                    and not (isinstance(d0,str) and (d0.startswith('**') or d0.startswith('*'))) # hack for callable as strings
                    # and not hasattr(d[0],'keys')
                ):
                    missing.add(d0)
            except UnicodeEncodeError:
                import warnings
                warnings.error('UnicodeDecodeError when processing data set '+repr(d[0]))
        if missing:
            if len(list(data.keys()))==0 or len(data[list(data.keys())[0]])==0: # no data at all yet, do not add garbage NaNs
                for m in missing: data[m]=[]
            else:
                addDataColumns(data,missing)
                try:
                    print('Missing columns in Scene.plot.data, added NaNs:',', '.join([m for m in missing]))
                except UnicodeDecodeError:
                    warnings.warn('UnicodeDecodeError reporting missing data columns -- harmless, just wondering...')
        def createLines(pStrip,ySpecs,axes,isY1=True,y2Exists=False):
            '''Create data lines from specifications; this code is common for y1 and y2 axes;
            it handles y-data specified as callables/dicts passed as string (starting with '*'/'**'), which might create additional lines when updated with liveUpdate.
            '''
            # save the original specifications; they will be smuggled into the axes object
            # the live updated will run yNameFuncs to see if there are new lines to be added
            # and will add them if necessary
            yNameFuncs=set()
            yNames=set()
            ySpecs2=[]
            for ys in ySpecs:
                if not isinstance(ys[0],(past.builtins.str,str)): raise ValueError('Plot specifications must be strings (not a %s).'%type(ys[0]))
                if ys[0].startswith('**') or ys[0].startswith('*'):
                    evEx=eval(ys[0][(2 if ys[0].startswith('**') else 1):],{'S':P.scene})
                    yNameFuncs.add(evEx)  # add callable or dictionary
                    # XXX: what is ys[1]? Previously, there was no line specifier there for dicts at least
                    # print evEx,type(evEx), evEx.__iter__(),type(evEx.__iter__())
                    ySpecs2+=[(ret,ys[1]) for ret in evEx] # traverse list or dict keys
                else: ySpecs2.append(ys)
            if len(ySpecs2)==0:
                print('woo.plot: creating fake plot, since there are no y-data yet')
                line,=axes.plot([nan],[nan])
                line2,=axes.plot([nan],[nan])
                if replace: P.currLineRefs.append(LineRef(line=line,scatter=None,annotation=None,line2=line2,xdata=[nan],ydata=[nan]))
            # set different color series for y1 and y2 so that they are recognizable
            if 'axes.color_cycle' in matplotlib.rcParams: matplotlib.rcParams['axes.color_cycle']='b,g,r,c,m,y,k' if not isY1 else 'm,y,k,b,g,r,c'
            for d in ySpecs2:
                yNames.add(d)
                # should have been handled above already
                #if pStrip not in data:
                #    print 'Missing column %s in Scene.plot.data, added NaN.'%pString
                #    addDataColumns(data,[pStrip])
                if d[0] not in data:
                    print('Missing column %s in Scene.plot.data, added NaN.'%d[0])
                    addDataColumns(data,[d[0]])
                line,=axes.plot(data[pStrip],data[d[0]],d[1],label=xlateLabel(d[0],P.labels),**lineKw)
                lineKwWithoutAlpha=dict([(k,v) for k,v in list(lineKw.items()) if k!='alpha'])
                line2,=axes.plot([],[],d[1],color=line.get_color(),alpha=afterCurrentAlpha,**lineKwWithoutAlpha)
                # use (0,0) if there are no data yet
                scatterPt=[0,0] if len(data[pStrip])==0 else (data[pStrip][current],data[d[0]][current])
                scatterPtPos=[scatterPt[0] if not math.isnan(scatterPt[0]) else 0,scatterPt[1] if not math.isnan(scatterPt[1]) else 0]
                # if current value is NaN, use zero instead
                scatter=axes.scatter(scatterPtPos[0],scatterPtPos[1],s=scatterSize,color=line.get_color(),**scatterMarkerKw)
                if annotateFmt:
                    if math.isnan(scatterPtPos[0]) or math.isnan(scatterPtPos[1]): text=''
                    else: text=annotateFmt.format(xy=scatterPt)
                    annotation=axes.annotate(text,xy=scatterPtPos,color=line.get_color(),**annotateKw)
                    annotation.annotateFmt=annotateFmt
                else: annotation=None
                if replace: P.currLineRefs.append(LineRef(line=line,scatter=scatter,annotation=annotation,line2=line2,xdata=data[pStrip],ydata=data[d[0]]))
            axes=_my_get_axes(line)
            labelLoc=(legendLoc[0 if isY1 else 1] if y2Exists>0 else 'best')
            l=axes.legend(loc=labelLoc)
            if l:
                l.get_frame().set_alpha(legendAlpha)
                if hasattr(l,'draggable'): l.draggable(True)
            if scientific:
                axes.ticklabel_format(style='sci',scilimits=(0,0),axis='both')
                # fixes scientific exponent placement for y2: https://sourceforge.net/mailarchive/forum.php?thread_name=20101223174750.GD28779%40ykcyc&forum_name=matplotlib-users
                if not isY1: axes.yaxis.set_offset_position('right')
            if isY1:
                axes.set_ylabel((', '.join([xlateLabel(_p[0],P.labels) for _p in ySpecs2])) if p not in xylabels or not xylabels[p][1] else xylabels[p][1])
                axes.set_xlabel(xlateLabel(pStrip,P.labels) if (p not in xylabels or not xylabels[p][0]) else xylabels[p][0])
            else:
                axes.set_ylabel((', '.join([xlateLabel(_p[0],P.labels) for _p in ySpecs2])) if (p not in xylabels or len(xylabels[p])<3 or not xylabels[p][2]) else xylabels[p][2])
            # if there are callable/dict ySpecs, save them inside the axes object, so that the live updater can use those
            if yNameFuncs:
                axes.wooYNames,axes.wooYFuncs,axes.wooXName,axes.wooLabelLoc=yNames,yNameFuncs,pStrip,labelLoc # prepend woo to avoid clashes
            if 0:
                # fix missing 'show' method; this has been fixed in matplotlib already, but we need to backport that
                # see https://github.com/matplotlib/matplotlib/commit/15fd0ae587a57cb1d7b69546eb359085315148c8
                # don't do that for headless backend, error there is fine
                fig=axes.get_figure()
                if not hasattr(fig,'show'):
                    mgr=getattr(fig.canvas,'manager')
                    if mgr: fig.show=lambda *args: mgr.window.show()
        createLines(pStrip,plots_p_y1,axes=axes,isY1=True,y2Exists=len(plots_p_y2)>0)
        if axesWd>0:
            axes.axhline(linewidth=axesWd,color='k')
            axes.axvline(linewidth=axesWd,color='k')
        # create y2 lines, if any
        if len(plots_p_y2)>0:
            axes=axes.twinx() # create the y2 axis
            createLines(pStrip,plots_p_y2,axes,isY1=False,y2Exists=True)
        ### scene is not directly accessible from here, do it like this:
        S=woo.master.scene
        if S.plot==P:
            if 'title' in S.tags: axes.set_title(S.tags['title'])
    return figs
Ejemplo n.º 8
0
 def update(self):
     if isinstance(self.line,matplotlib.image.AxesImage):
         # image name
         try:
             if len(self.xdata)==0 and self.dataName: self.xdata=self.imgData[self.dataName]  # empty list reference an empty singleton, not the list we want; adjust here
             import Image
             if self.xdata[current]==None: img=Image.new('RGBA',(1,1),(0,0,0,0))
             else: img=Image.open(self.xdata[current])
             self.line.set_data(img)
         except IndexError: pass
     else:
         # regular data
         import numpy
         # current==-1 avoids copy slicing data in the else part
         if current==None or current==-1 or afterCurrentAlpha==1:
             self.line.set_xdata(self.xdata); self.line.set_ydata(self.ydata)
             self.line2.set_xdata([]); self.line2.set_ydata([])
         else:
             try: # try if we can extend the first part by one so that lines are connected
                 self.xdata[:current+1]; preCurrEnd=current+1
             except IndexError: preCurrEnd=current
             preCurrEnd=current+(1 if len(self.xdata)>current else 0)
             self.line.set_xdata(self.xdata[:preCurrEnd]); self.line.set_ydata(self.ydata[:preCurrEnd])
             self.line2.set_xdata(self.xdata[current:]); self.line2.set_ydata(self.ydata[current:])
         try:
             x,y=self.xdata[current],self.ydata[current]
         except IndexError: x,y=0,0
         # this could be written in a nicer way, very likely
         try:
             pt=numpy.ndarray((2,),buffer=numpy.array([float(x),float(y)]))
             if self.scatter:
                 self.scatter.set_offsets(pt)
                 # change rotation of the marker (possibly incorrect)
                 try:
                     dx,dy=self.xdata[current]-self.xdata[current-1],self.ydata[current]-self.ydata[current-1]
                     # smoothing from last n values, if possible
                     # FIXME: does not show arrow at all if less than window values
                     #try:
                     #    window=10
                     #    dx,dy=[numpy.average(numpy.diff(dta[current-window:current])) for dta in self.xdata,self.ydata]
                     #except IndexError: pass
                     # there must be an easier way to find on-screen derivative angle, ask on the matplotlib mailing list
                     # XXX: this can be siplified once we drop support for matplotlib < 1.5
                     # XXX: and is here to avoid MatplotlibDeprecationWarning for newer versions
                     axes=_my_get_axes(self.line)
                     p=axes.patch; xx,yy=p.get_verts()[:,0],p.get_verts()[:,1]; size=max(xx)-min(xx),max(yy)-min(yy)
                     aspect=(size[1]/size[0])*(1./axes.get_data_ratio())
                     if dx==0: angle=math.pi
                     angle=math.atan(aspect*dy/dx)
                     if dx<0: angle-=math.pi
                     self.scatter.set_transform(matplotlib.transforms.Affine2D().rotate(angle))
                 except IndexError: pass
             if self.annotation:
                 if math.isnan(x) or math.isnan(y):
                     if hasattr(self.annotation,'xyann'): self.annotation.xyann=(x,y)
                     else: self.annotation.xytext=(0,0)
                     self.annotation.set_text('') # make invisible, place anywhere
                 else:
                     #
                     if hasattr(self.annotation,'xyann'): self.annotation.xyann=(x,y) # newer MPL versions (>=1.4)
                     else: self.annotation.xyann=(x,y)
                     self.annotation.set_text(self.annotation.annotateFmt.format(xy=(float(x),float(y))))
         except TypeError: pass # this happens at i386 with empty data, saying TypeError: buffer is too small for requested array