Exemple #1
0
def plot_counts(ax, dictorigin, x_locator, x_formatter, bin_edges_in, snum, enum):
    # compute all data needed
    time = dictorigin["time"]
    cumcounts = np.arange(1, np.alen(time) + 1)
    if len(bin_edges_in) < 2:
        return
    binsize = bin_edges_in[1] - bin_edges_in[0]
    binsize_str = binsizelabel(binsize)

    # plot
    counts, bin_edges_out, patches = ax.hist(
        time, bin_edges_in, cumulative=False, histtype="bar", color="black", edgecolor=None
    )
    ax.grid(True)
    ax.xaxis_date()
    plt.setp(ax.get_xticklabels(), rotation=90, horizontalalignment="center", fontsize=7)
    ax.set_ylabel("# Earthquakes\n%s" % binsize_str, fontsize=8)
    ax.xaxis.set_major_locator(x_locator)
    ax.xaxis.set_major_formatter(x_formatter)
    if snum and enum:
        ax.set_xlim(snum, enum)

    ax2 = ax.twinx()
    p2, = ax2.plot(time, cumcounts, "g", lw=2.5)
    ax2.yaxis.get_label().set_color(p2.get_color())
    ytl_obj = plt.getp(ax2, "yticklabels")  # get the properties for yticklabels
    # plt.getp(ytl_obj)                       # print out a list of properties
    plt.setp(ytl_obj, color="g")  # set the color of yticks to red
    plt.setp(plt.getp(ax2, "yticklabels"), color="g")  # xticklabels: same
    ax2.set_ylabel("Cumulative\n# Earthquakes", fontsize=8)
    ax2.xaxis.set_major_locator(x_locator)
    ax2.xaxis.set_major_formatter(x_formatter)
    if snum and enum:
        ax2.set_xlim(snum, enum)
    return
Exemple #2
0
def fplotly(fig, username, api_key):
    axes = fig.axes
    lines = axes[0].lines
    xdata = plt.getp(lines[0], 'xdata')
    ydata = plt.getp(lines[0], 'ydata')
    py = plotly.plotly(username, api_key)
    py.plot(xdata,ydata)
Exemple #3
0
def insax(ax, i, j, h, w, **kwargs):
    """
    Axes spanning upper left spij(m,n,i,j) to lower right spij(m,n,i+h-1,j+w-1).
    
    ax is a (nrow, ncol) array of Axes.
    
    Example (using a new figure to avoid interference with any existing figure 
    objects).
    
    >>> fig = plt.figure()
    >>> ax = np.array([plt.subplot(4, 4, i) for i in range(1, 17)], 
    ...     object).reshape(4, 4)
    >>> pos = getp(insax(ax, 1, 1, 2, 2), "position")
    >>> print str(pos).replace("'", "")
    Bbox(array([[ 0.32717391,  0.30869565],...[ 0.69782609,  0.69130435]]))
    """
    (left, _), (_, top) = getp(ax[i, j], "position").get_points()
    (_, bottom), (right, _) = getp(ax[i+h-1, j+w-1], "position").get_points()
    # (left, _), (_, top) = getp(spij(m, n, i, j), "position").get_points()
    # (_, bottom), (right, _) = getp(
    #     spij(m, n, i+h, j+w), "position").get_points()
    width = right - left
    height = top - bottom
    ax = plt.gcf().add_axes([left, bottom, width, height], **kwargs)
    return ax
Exemple #4
0
def plotStreamLine(x,y,U,V,nIter):
   pltFile = 'streamLine_%5.5d.png' % int(nIter)
   x = np.asarray(x)
   y = np.asarray(y)
   U = np.swapaxes(U,1,0)
   V = np.swapaxes(V,1,0)

   strm = plt.streamplot(x,y,U,V, color='k', density=1, linewidth=1)

   plt.axis([x.min(), x.max(), y.min(), y.max()])
   plt.xscale('linear')
   plt.yscale('linear')
   plt.xlabel('x [m]', fontsize=18)
   plt.ylabel('y [m]', fontsize=18)
   plt.grid(True)
   ax = plt.gca()
   xlabels = plt.getp(ax, 'xticklabels')
   ylabels = plt.getp(ax, 'yticklabels')
   plt.setp(xlabels, fontsize=10)
   plt.setp(ylabels, fontsize=10)

   fig = plt.gcf()
   fig.set_size_inches(5,6)
   plt.tight_layout()
   plt.savefig(pltFile, format='png')
   plt.close()

   print "%s DONE!!" % (pltFile)
   plt.show()
Exemple #5
0
def plotTempContour(x,y,T,nIter):
   from matplotlib import mlab, cm
   cmap = cm.PRGn

   pltFile = 'contour_Temp_%5.5d.png' % int(nIter)
   x = np.asarray(x)
   y = np.asarray(y)

   phiMin = T.min()
   phiMax = T.max()

   plt.imshow(T, vmin=phiMin, vmax=phiMax, extent=[x.min(), x.max(), y.min(), y.max()])
   plt.colorbar()

   plt.xscale('linear')
   plt.yscale('linear')
   plt.xlabel('x', fontsize=18)
   plt.ylabel('y', fontsize=18)
   #plt.grid(True)
   ax = plt.gca()
   xlabels = plt.getp(ax, 'xticklabels')
   ylabels = plt.getp(ax, 'yticklabels')
   plt.setp(xlabels, fontsize=15)
   plt.setp(ylabels, fontsize=15)

   fig = plt.gcf()
   fig.set_size_inches(9,5)
   plt.tight_layout()
   plt.savefig(pltFile, format='png')
   plt.close()

   print "%s DONE!!" % (pltFile)
   plt.show()
Exemple #6
0
def plotContour(x,y,phi,pltFile):
   xi, yi = np.meshgrid(x, y)
   zi = phi

   plt.imshow(zi, vmin=zi.min(), vmax=0.075, origin='lower', extent=[x.min(), x.max(), y.min(), y.max()])
   plt.colorbar()

   plt.xscale('linear')
   plt.yscale('linear')
   plt.xlabel('x', fontsize=18)
   plt.ylabel('y', fontsize=18)
   plt.grid(True)
   ax = plt.gca()
   xlabels = plt.getp(ax, 'xticklabels')
   ylabels = plt.getp(ax, 'yticklabels')
   plt.setp(xlabels, fontsize=15)
   plt.setp(ylabels, fontsize=15)

   fig = plt.gcf()
   fig.set_size_inches(6,5)
   plt.tight_layout()
   plt.savefig(pltFile, format='png')
   plt.close()

   print "%s DONE!!" % (pltFile)
   plt.show()
Exemple #7
0
def plot_energy(ax, dictorigin, x_locator, x_formatter, bin_edges, snum, enum):

    # compute all data needed
    time = dictorigin["time"]
    energy = ml2energy(dictorigin["ml"])
    cumenergy = np.cumsum(energy)
    binned_energy = bin_irregular(time, energy, bin_edges)
    if len(bin_edges) < 2:
        return
    barwidth = bin_edges[1:] - bin_edges[0:-1]
    binsize = bin_edges[1] - bin_edges[0]
    binsize_str = binsizelabel(binsize)

    # plot
    ax.bar(bin_edges[:-1], binned_energy, width=barwidth, color="black", edgecolor=None)

    # re-label the y-axis in terms of equivalent Ml rather than energy
    yticklocs1 = ax.get_yticks()
    ytickvalues1 = np.log10(yticklocs1) / 1.5
    yticklabels1 = list()
    for count in range(len(ytickvalues1)):
        yticklabels1.append("%.2f" % ytickvalues1[count])
    ax.set_yticks(yticklocs1)
    ax.set_yticklabels(yticklabels1)

    ax.grid(True)
    ax.xaxis_date()
    plt.setp(ax.get_xticklabels(), rotation=90, horizontalalignment="center", fontsize=7)
    ax.set_ylabel("Energy %s\n(unit: Ml)" % binsize_str, fontsize=8)
    ax.xaxis.set_major_locator(x_locator)
    ax.xaxis.set_major_formatter(x_formatter)
    if snum and enum:
        ax.set_xlim(snum, enum)

    # Now add the cumulative energy plot - again with yticklabels as magnitudes
    ax2 = ax.twinx()
    p2, = ax2.plot(time, cumenergy, "g", lw=2.5)

    # use the same ytick locations as for the left-hand axis, but label them in terms of equivalent cumulative magnitude
    yticklocs1 = ax.get_yticks()
    yticklocs2 = (yticklocs1 / max(ax.get_ylim())) * max(ax2.get_ylim())
    ytickvalues2 = np.log10(yticklocs2) / 1.5
    yticklabels2 = list()
    for count in range(len(ytickvalues2)):
        yticklabels2.append("%.2f" % ytickvalues2[count])
    ax2.set_yticks(yticklocs2)
    ax2.set_yticklabels(yticklabels2)

    ax2.yaxis.get_label().set_color(p2.get_color())
    ytl_obj = plt.getp(ax2, "yticklabels")  # get the properties for yticklabels
    # plt.getp(ytl_obj)                       # print out a list of properties
    plt.setp(ytl_obj, color="g")  # set the color of yticks to red
    plt.setp(plt.getp(ax2, "yticklabels"), color="g")  # xticklabels: same
    ax2.set_ylabel("Cumulative Energy\n(unit: Ml)", fontsize=8)
    ax2.xaxis.set_major_locator(x_locator)
    ax2.xaxis.set_major_formatter(x_formatter)
    if snum and enum:
        ax2.set_xlim(snum, enum)
    return
Exemple #8
0
	def plot_trace(self, elec, raw = 'CAR', Params = dict()):
		"""
		plots trace for the trial duration using TrialsMTX
		INPUT:
			elec - electrode number
			raw - if to calculate from raw trace ('CAR') or from hilbert ('hilbert') - optional, default 'CAR'
			Params - dictionary of onset/offset times for trial and for baseline. (optional)
		"""
		#default Params
		if not Params: #empty dict
			print 'loading default Params'
			Params['st'] = 0		#start time point (ms)
			Params['en'] = 3000		#end time point (ms)
			Params['bl_st'] = -250	#baseline start (ms)
			Params['bl_en'] = -50	#basline end (ms)
		
		dataMTX = self.makeTrialsMTX(elec, raw, Params)

		st = int(round(Params['st'] / 1000 * self.srate))
		en = int(round(Params['en'] / 1000 * self.srate))
		bl_st = int(round(Params['bl_st'] / 1000 * self.srate))
		bl_en = int(round(Params['bl_en'] / 1000 * self.srate))
		
		x = np.arange(st, en)

		plot_tp = 250 / 1000 * self.srate #ticks every 250 ms
		cue = 500 / 1000 * self.srate
		
		f, ax = plt.subplots(1,1)
		ax.axhline(y = 0,color = 'k',linewidth=2)
		ax.axvline(x = 0,color='k',linewidth=2)
		ax.axvline(x = cue,color = 'gray',linewidth = 2)
		ax.axvline(x = cue+cue,color = 'gray',linewidth = 2)
		ax.axvspan(cue, cue+cue, facecolor='0.5', alpha=0.25,label = 'cue')

		ax.plot(x, np.mean(dataMTX,0), linewidth = 2, color = 'blue')

		ax.set_xlim(st, en)
		ax.xaxis.set_ticklabels(['0', '','500', '', '1000', '', '1500', '', '2000','','2500','', '3000'],minor=False)
		ax.xaxis.set_ticks(np.arange(st, en, plot_tp))
		ax.xaxis.set_tick_params(labelsize = 14)
		ax.yaxis.set_tick_params(labelsize=14)
		xticklabels = plt.getp(plt.gca(), 'xticklabels')
		yticklabels = plt.getp(plt.gca(), 'yticklabels')
		plt.setp(xticklabels, fontsize=14, weight='bold')
		plt.setp(yticklabels, fontsize=14, weight='bold')

		for pos in ['top','bottom','right','left']:
			ax.spines[pos].set_edgecolor('gray')
			ax.get_xaxis().tick_bottom()
			ax.get_yaxis().tick_left()

		ax.set_xlabel("time (ms)")
		ax.set_ylabel("uV")
		ax.set_title('raw trace - electrode: %i' %(elec), fontsize = 18)
		plt.show()
Exemple #9
0
def display2Dpointsets(A, B):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(A[:,0],A[:,1],'yo',markersize=8,mew=1)
    ax.plot(B[:,0],B[:,1],'b+',markersize=8,mew=1)
    labels = plt.getp(plt.gca(), 'xticklabels')
    plt.setp(labels, color='k', fontweight='bold')
    labels = plt.getp(plt.gca(), 'yticklabels')
    plt.setp(labels, color='k', fontweight='bold')
    return None
Exemple #10
0
def make_positivity_plot(nga,fileNameList,cd3ChanIndex,figName,emResults,subset='CD3',filterID=None):

    filesToPlot = fileNameList
    if len(fileNameList) > 6:
        filesToPlot = fileNameList[:6]

    fig = plt.figure()
    fontSize = 8
    pltCount = 0

    for fileName in filesToPlot:
        events = nga.get_events(fileName)
        if filterID != None:
            filterIndices = nga.get_filter_indices(fileName,filterID)
            events = events[filterIndices,:] 

        cd3Events = events[:,cd3ChanIndex]
        pltCount+=1
        if pltCount > 6:
            continue

        ax = fig.add_subplot(2,3,pltCount)
        eCDF = EmpiricalCDF(cd3Events)
        thresholdLow = eCDF.get_value(0.05)
        eventsInHist = cd3Events[np.where(cd3Events > thresholdLow)[0]]
        n, bins, patches = ax.hist(eventsInHist,18,normed=1,facecolor='gray',alpha=0.5)

        maxX1 = cd3Events.max()
        maxX2 = cd3Events.max()
        pdfX1 = np.linspace(0,maxX1,300)
        pdfY1 = stats.norm.pdf(pdfX1,emResults[fileName]['params']['mu1'], np.sqrt(emResults[fileName]['params']['sig1']))
        pdfX2 = np.linspace(0,maxX2,300)
        pdfY2 = stats.norm.pdf(pdfX2,emResults[fileName]['params']['mu2'], np.sqrt(emResults[fileName]['params']['sig2']))
        pdfY1 = pdfY1 * (1.0 - emResults[fileName]['params']['pi'])
        pdfY1[np.where(pdfY1 < 0)[0]] = 0.0
        pdfY2 = pdfY2 * emResults[fileName]['params']['pi']
        pdfY2[np.where(pdfY2 < 0)[0]] = 0.0

        ax.plot(pdfX1, pdfY1, 'k-', linewidth=2)
        ax.plot(pdfX2, pdfY2, 'k-', linewidth=2)
        threshY = np.linspace(0,max([max(pdfY1),max(pdfY2)]),100)
        threshX = np.array([emResults[fileName]['cutpoint']]).repeat(100)
        ax.plot(threshX, threshY, 'r-', linewidth=2)
        ax.set_title(fileName,fontsize=9)
        xticklabels = plt.getp(plt.gca(),'xticklabels')
        yticklabels = plt.getp(plt.gca(),'yticklabels')
        plt.setp(xticklabels, fontsize=fontSize-1)
        plt.setp(yticklabels, fontsize=fontSize-1)

        ax.set_xlabel(round(emResults[fileName]['params']['likelihood']))

        ax.set_xticks([])

    fig.subplots_adjust(hspace=0.3,wspace=0.3)
    plt.savefig(figName)
Exemple #11
0
def display2Dpointset(A):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(A[:,0],A[:,1],'yo',markersize=8,mew=1)
    labels = plt.getp(plt.gca(), 'xticklabels')
    plt.setp(labels, color='k', fontweight='bold')
    labels = plt.getp(plt.gca(), 'yticklabels')
    plt.setp(labels, color='k', fontweight='bold')
    for i,x in enumerate(A):
        ax.annotate('%d'%(i+1), xy = x, xytext = x + 0)
    return None
Exemple #12
0
def plotSolution(time):
   x = domainVars.x
   phi = flowVars.phi
   exac = flowVars.exac
   imax = len(phi)
   pltFile = 'solution_%5.3f.png' % float(time)
   MinX = min(x)
   MaxX = max(x)
   MinY = -0.1#min(phi)
   MaxY = 1.0#1.1*max(phi)

   p = plt.plot(x,phi, 'k-', label='Numerical solution')
   p = plt.plot(x,exac, 'r--', label='Exact solution')
   plt.setp(p, linewidth='3.0')

   plt.axis([MinX,MaxX, MinY, MaxY])
   plt.xscale('linear')
   plt.yscale('linear')
   plt.xlabel('x', fontsize=22)
   plt.ylabel('phi', fontsize=22)

   plt.grid(True)
   #plt.text(0.01, 0.2, 'Grid size = %s' % len(phi), fontsize=22 )
   ax = plt.gca()
   xlabels = plt.getp(ax, 'xticklabels')
   ylabels = plt.getp(ax, 'yticklabels')
   plt.setp(xlabels, fontsize=18)
   plt.setp(ylabels, fontsize=18)
   plt.legend(
             loc='upper right',
             borderpad=0.25,
             handletextpad=0.25,
             borderaxespad=0.25,
             labelspacing=0.0,
             handlelength=2.0,
             numpoints=1)
   legendText = plt.gca().get_legend().get_texts()
   plt.setp(legendText, fontsize=18)
   legend = plt.gca().get_legend()
   legend.draw_frame(False)

   fig = plt.gcf()
   fig.set_size_inches(8,5)
   plt.tight_layout()
   plt.savefig(pltFile, format='png')
   plt.close()

   print "%s DONE!!" % (pltFile)

   # write a CSVfile
   csvFile = 'solution_%5.3f.csv' % float(time)
   writeCSV(csvFile,x,phi,exac)
Exemple #13
0
def display2Dpointsets(A, B, ax = None):
    """ display a pair of 2D point sets """
    if not ax:
        fig = plt.figure()
        ax = fig.add_subplot(111)

    ax.plot(A[:,0],A[:,1],'yo',markersize=8,mew=1)
    ax.plot(B[:,0],B[:,1],'b+',markersize=8,mew=1)
    #pylab.setp(pylab.gca(), 'xlim', [-0.15,0.6])
    labels = plt.getp(plt.gca(), 'xticklabels')
    plt.setp(labels, color='k', fontweight='bold')
    labels = plt.getp(plt.gca(), 'yticklabels')
    plt.setp(labels, color='k', fontweight='bold')
 def _update_segment(self):
     segments = self.marker.get_segments()
     segments[0][0, 0] = self.get_data_position('x1')
     segments[0][1, 0] = segments[0][0, 0]
     if self.get_data_position('y1') is None:
         segments[0][0, 1] = plt.getp(self.marker.axes, 'ylim')[0]
     else:
         segments[0][0, 1] = self.get_data_position('y1')
     if self.get_data_position('y2') is None:
         segments[0][1, 1] = plt.getp(self.marker.axes, 'ylim')[1]
     else:
         segments[0][1, 1] = self.get_data_position('y2')
     self.marker.set_segments(segments)
Exemple #15
0
def set_ticks_fontsize(fontsize, colbar=None):
    """ Change the fontsize of the tick labels for the current figure.
    If colorbar (Colorbar instance) is provided then change the fontsize of its
    tick labels as well.
    """

    yticklabels = plt.getp(plt.gca(), 'yticklabels')
    plt.setp(yticklabels, 'color', 'k', fontsize=fontsize)
    xticklabels = plt.getp(plt.gca(), 'xticklabels')
    plt.setp(xticklabels, 'color', 'k', fontsize=fontsize)

    if colbar is not None:
        ticklabels = plt.getp(colbar.ax, 'yticklabels')
        plt.setp(ticklabels, 'color', 'k', fontsize=fontsize)
Exemple #16
0
def plotSolutions(x,phi,exact):
   imax = len(x)
   pltFile = 'prob1Solution.png'
   #MinX = min(x)
   #MaxX = max(x)
   #MinY = min(exact)
   #MaxY = 1.1*max(phi)
   MinX = 0.65
   MaxX = 0.9*max(x)
   MinY = 0.6
   MaxY = 1.0

   p = plt.plot(x,phi, 'k-', label='Numerical solution')
   plt.setp(p, linewidth='3.0')
   p = plt.plot(x,exact, 'r--', label='Analytical solution')

   plt.setp(p, linewidth='3.0')
   plt.axis([MinX,MaxX, MinY, MaxY])
   plt.xscale('linear')
   plt.yscale('linear')
   plt.xlabel('x', fontsize=22)
   plt.ylabel('phi', fontsize=22)

   plt.grid(True)
   plt.text(0.67, 0.7, 'Grid size = %s' % len(phi), fontsize=22 )
   ax = plt.gca()
   xlabels = plt.getp(ax, 'xticklabels')
   ylabels = plt.getp(ax, 'yticklabels')
   plt.setp(xlabels, fontsize=18)
   plt.setp(ylabels, fontsize=18)
   plt.legend(
             loc='lower left',
             borderpad=0.25,
             handletextpad=0.25,
             borderaxespad=0.25,
             labelspacing=0.0,
             handlelength=2.0,
             numpoints=1)
   legendText = plt.gca().get_legend().get_texts()
   plt.setp(legendText, fontsize=18)
   legend = plt.gca().get_legend()
   legend.draw_frame(False)

   fig = plt.gcf()
   fig.set_size_inches(5,5)
   plt.tight_layout()
   plt.savefig(pltFile, format='png')
   plt.close()

   print "%s DONE!!" % (pltFile)
Exemple #17
0
def plot_vj_joint_dist( handle, savefilename="VJusage", tags_v = open("tags_trbv.txt", "rU"), tags_j = open("tags_trbj.txt", "rU")):

    ## PLOTS VJ JOINT GENE USAGE BASED ON A FILE OF CLASSIFIERS
    
    import numpy as np
    import matplotlib.pyplot as plt
    import string
    import decimal as dec

    num_v = 0
    for line in tags_v:
        num_v += 1

    num_j = 0
    for line in tags_j:
        num_j += 1
        
    joint_distribution = np.zeros((num_v,num_j))
    for line in handle:
        elements = line.rstrip("\n")

        v = int(string.split(elements)[0])
        j = int(string.split(elements)[1])

        joint_distribution[v,j] += 1

    joint_distribution = joint_distribution / sum(sum(joint_distribution))
    gene_list_v = ('V10-1', 'V10-2', 'V10-3', 'V11-1', 'V11-2', 'V11-3', 'V12-3/V12-4', 'V12-5', 'V13', 'V14', 'V15', 'V16', 'V18', 'V19', 'V2', 'V20-1', 'V24-1', 'V25-1', 'V27-1', 'V28-1', 'V29-1', 'V3-1', 'V30-1', 'V4-1', 'V4-2', 'V4-3', 'V5-1', 'V5-4', 'V5-5', 'V5-6', 'V5-8', 'V6-1', 'V6-4', 'V6-5', 'V6-6', 'V6-8', 'V6-9', 'V7-2', 'V7-3', 'V7-4', 'V7-6', 'V7-7', 'V7-8', 'V7-9', 'V9')
    gene_list_j = ('J1-1', 'J1-2', 'J1-3', 'J1-4', 'J1-5', 'J1-6', 'J2-1', 'J2-2', 'J2-3', 'J2-4', 'J2-5', 'J2-6', 'J2-7')

    pos_v = np.arange(num_v)+ 1
    pos_j = np.arange(num_j)+ 1
    
    plt.figure()
    plt.pcolor(joint_distribution)
    pos_ticks_v = pos_v-0.5
    pos_ticks_j = pos_j-0.5
    plt.yticks( pos_ticks_v, gene_list_v)
    plt.xticks( pos_ticks_j, gene_list_j)
    plt.colorbar()
    plt.pcolor(joint_distribution)
    yticklabels = plt.getp(plt.gca(), 'yticklabels')
    plt.setp(yticklabels, fontsize='8')
    xticklabels = plt.getp(plt.gca(), 'xticklabels')
    plt.setp(xticklabels, fontsize='8')
    plt.savefig(str(savefilename)+'.png', dpi=300)

    handle.close()
    tags_v.close()
    tags_j.close()
Exemple #18
0
def plot_parameter_sweep(exp_lambda, parameters, error=False, xaxis="", yaxis="", title="", filename="output.png"):

    import matplotlib.pyplot as plt
    from matplotlib import font_manager, rcParams

    plt.figure()

    X = parameters
    Y1 = []
    E1 = []

    Y2 = []
    E2 = []

    Y3 = []
    E3 = []

    for x in X:
        result = exp_lambda(x)
        Y1.append(result[0][0])
        E1.append(result[1][0])

        Y2.append(result[0][1])
        E2.append(result[1][1])

        Y3.append(result[0][3])
        E3.append(result[1][3])

    rcParams.update({"font.size": 22})

    fprop = font_manager.FontProperties(fname="/Library/Fonts/Microsoft/Gill Sans MT.ttf")

    plt.plot(X, Y1, "s-", linewidth=2.5, markersize=16, color="#3399FF")

    if not error:
        plt.plot(X, Y2, "o-", linewidth=2.5, markersize=16, color="#FF6666")
    else:
        plt.plot(X, Y3, "o-", linewidth=2.5, markersize=16, color="#FF6666")
        # plt.plot(X, Y3, '--')
    plt.title(title, fontproperties=fprop)
    plt.xlabel(xaxis, fontproperties=fprop)
    plt.ylabel(yaxis, fontproperties=fprop)
    xticklabels = plt.getp(plt.gca(), "xticklabels")
    xticklabels = plt.getp(plt.gca(), "yticklabels")
    plt.setp(xticklabels, fontproperties=fprop)
    # plt.legend(['PrivateClean','Naive', 'Dirty'], loc='upper left')
    plt.grid(True)
    plt.savefig(filename)
def plot_density2d(hist, extent, xlim, ylim, xlabel, ylabel, cmap='brg'):
	fig = plt.figure()
	plt.subplots_adjust(bottom=0.15, right=1, left=0.15)
	
	#Smoothing of histogram
	#z = ndimage.gaussian_filter(hist, sigma=0.8, order=0)

	#Plotting contour
	CS = plt.contour(hist, extent=extent, linewidths=1,colors='k', zorder=1000)
	CS = plt.contourf(hist, extent=extent, cmap=cmap)
	
	# Inline contour label
	#P.clabel(CS,inline=1,fmt='%1.1f',fontsize=16,fontname="Times new roman")

	plt.tick_params(axis='both',which='major',width=2,length=15)
	plt.tick_params(axis='both',which='minor',width=2,length=10)
	plt.xlabel(xlabel,fontsize="24", fontname="Times new roman")
	plt.ylabel(ylabel, fontsize="24", fontname = "Times new roman")
	ax = plt.gca()
	plt.xticks(ax.get_xticks()[::2], fontsize="24", fontname = "Times new roman")
	plt.yticks(ax.get_yticks(), fontsize="24", fontname = "Times new roman")
	plt.xlim(extent[0],extent[1])	
	plt.ylim(extent[2],extent[3])
	cb = plt.colorbar()	
	
	# Color bar
	cb_yticks = plt.getp(cb.ax.axes, 'yticklabels')
	plt.setp(cb_yticks, fontsize=24, fontname = "times new roman")
	
	plt.savefig('{0}_density.png' .format(sys.argv[2]),orientation='landscape',dpi=300, papertype='a4')
def grad_dist(curdata,ax):
    #gaussian kernel density estimation           
    x=np.linspace(0,90,91)
    kde=gaussian_kde(curdata)
    line,=ax.plot(x,kde(x), '-', label=hl[j][0:-2]+"0")
    curcolor=plt.getp(line,'color')

##    #plotting histogram
##    ax.hist(curdata,bins=int(max(curdata))+1,
##             normed=True, histtype='step',
##             color=curcolor, linewidth=0.5)

    #defining splines for kd function and corresponding 1st and seconde derivatives
    x=np.linspace(0,90,901)
    s=UnivariateSpline(x,kde(x),s=0,k=3)
    s1=UnivariateSpline(x,s(x,1),s=0,k=3)
    s2=UnivariateSpline(x,s1(x,1),s=0,k=3)

    #identifying local maxima (where s1=0, s2<0, and s>0.005)
    maxima=s1.roots()[np.where(s2(s1.roots())<0)[0]]
    maxima=maxima[np.where(s(maxima)>0.005)[0]]
    #s_max=maxima[-1]
    s_max=maxima[np.argmax(s(maxima))]
    ax.plot(s_max, s(s_max),'o', color=curcolor)

    #identifying steepest segment after maxima (where x>=maxima, s1<0)
    x2=x[np.where(x>=s_max)[0]]
    slope=s1(x2)
    s1_min=x2[np.argmin(slope)]
    ax.plot(s1_min,s(s1_min),'o', color=curcolor)

    print round(s_max,1),round(s1_min,1)

    return round(s_max,1),round(s1_min,1)
Exemple #21
0
def add_plot(mom, cfg):
    ax = mom['ax']
    levels = mom['levels']
    if cfg['contour']:
        im = ax.contourf(mom['data'], levels=levels,
                         colors=cfg['colors'], origin='lower', axis='equal',
                         extent=[cfg['dt_start'], cfg['dt_stop'],
                                 -0.11, cfg['beam_height'][-1]])
    else:
        cmap = ListedColormap(cfg['colors'])  # , name='')
        norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
        im = ax.pcolormesh(cfg['X'], cfg['Y'], mom['data'], cmap=cmap, norm=norm)

    ax.set_ylim(0, 13)
    ax.xaxis_date()
    ax.xaxis.set_major_formatter(mdates.DateFormatter('\n%H:%M'))
    ax.xaxis.set_major_locator(mdates.HourLocator())
    ax.xaxis.set_minor_formatter(mdates.DateFormatter('%M'))
    ax.xaxis.set_minor_locator(
        mdates.MinuteLocator(byminute=(15, 30, 45, 60)))
    ax.grid()
    ax.set_ylabel('Height (km)')
    ax.set_xlabel('Time (UTC)')

    cb = mom['fig'].colorbar(im, orientation='vertical', pad=0.018, aspect=35)
    cb.outline.set_visible(False)
    cbarytks = plt.getp(cb.ax.axes, 'yticklines')
    plt.setp(cbarytks, visible=False)
    cb.set_ticks(levels[0:-1])
    cb.set_ticklabels(["%.2f" % lev for lev in levels[0:-1]])
    cb.set_label(mom['cb_label'])
Exemple #22
0
def draw_colorbar(fig, ax, coll, ticks=None, cblabel="", cbar_pos=None, 
                  cb_fmt="%i", labelsize=12, pm=False):
    """ Draws the colorbar in a figure. """
    if cbar_pos is None:
        cbar_pos=[0.14, 0.13, 0.17, 0.04]
    cbaxes = fig.add_axes(cbar_pos)
    cbar = plt.colorbar(coll, cax=cbaxes, orientation='horizontal',
                        format=cb_fmt)
    cbar.set_ticks(ticks)
    cbar.ax.set_xlabel(cblabel)
    cbar.ax.xaxis.set_label_position('top')
    cbar.ax.xaxis.set_ticks_position('bottom')
    cbar.set_label(cblabel,size=labelsize)
    if pm:
        newticks = []
        for i,l in enumerate(cbar.ax.get_xticklabels()):
            label = str(l)[10:-2]
            if i == 0:
                newticks.append(r"$\leq${0}".format(label))
            elif i+1 == len(cbar.ax.get_xticklabels()):
                newticks.append(r"$\geq${0}".format(label))
            else:
                newticks.append(r"{0}".format(label))
        cbar.ax.set_xticklabels(newticks)
    cl = plt.getp(cbar.ax, 'xmajorticklabels')
    plt.setp(cl, fontsize=10)     
    return
Exemple #23
0
    def getp(self, prop):
        """Get line property value.

        Keyword arguments:
        prop -- Property name.
        """
        return plt.getp(self.line, prop)
Exemple #24
0
    def plot_BPR(self, algorithm, ax, label = None, decalage=None,**kwarks):
        '''
        plot detection results for a given algorithm
        '''

        if label==None:
            label = str(algorithm)
        KG = self.KG[algorithm.noiseType]
        try:
            detection = KG[str(algorithm)]
        except KeyError as e:
            print('No calculation for', algorithm)
            raise(e)
        else:
            if decalage:
                t=[]
                for i in detection['t']:
                    t.append(decalage+i)
            else:
                t=detection['t']
            logBPR= 10*np.log10(1+detection['avBPR'])
            l, = ax.plot(t,logBPR,\
                        label=label,**kwarks)
            ax.axhline(algorithm.param['threshold'],lw=1, color = plt.getp(l,'color'))
            ax.set_xlim([min(t),max(t)])
            ax.set_ylabel('BPR')
            ax.set_xlabel('t (s)')
            ax.set_ylim([min(logBPR),max(logBPR)*1.1])
Exemple #25
0
    def _draw_main_solution(self):
        """
        plot the solution at the finest level on our optional
        visualization
        """
        myg = self.grids[self.nlevels - 1].grid

        v = self.grids[self.nlevels - 1].get_var("v")

        plt.imshow(
            np.transpose(v[myg.ilo : myg.ihi + 1, myg.jlo : myg.jhi + 1]),
            interpolation="nearest",
            origin="lower",
            extent=[self.xmin, self.xmax, self.ymin, self.ymax],
        )

        plt.xlabel("x")
        plt.ylabel("y")
        plt.title(r"current fine grid solution")

        formatter = matplotlib.ticker.ScalarFormatter(useMathText=True)
        cb = plt.colorbar(format=formatter, shrink=0.5)

        cb.ax.yaxis.offsetText.set_fontsize("small")
        cl = plt.getp(cb.ax, "ymajorticklabels")
        plt.setp(cl, fontsize="small")
Exemple #26
0
    def _draw_solution(self):
        """ plot the current solution on our optional visualization """
        myg = self.grids[self.current_level].grid

        v = self.grids[self.current_level].get_var("v")

        cm = "viridis"

        plt.imshow(np.transpose(v[myg.ilo:myg.ihi+1, myg.jlo:myg.jhi+1]),
                   interpolation="nearest", origin="lower",
                   extent=[self.xmin, self.xmax, self.ymin, self.ymax], cmap=cm)

        # plt.xlabel("x")
        plt.ylabel("y")

        if self.current_level == self.nlevels-1:
            plt.title(r"solving $L\phi = f$")
        else:
            plt.title(r"solving $Le = r$")

        formatter = matplotlib.ticker.ScalarFormatter(useMathText=True)
        cb = plt.colorbar(format=formatter, shrink=0.5)

        cb.ax.yaxis.offsetText.set_fontsize("small")
        cl = plt.getp(cb.ax, 'ymajorticklabels')
        plt.setp(cl, fontsize="small")
Exemple #27
0
    def _draw_main_error(self):
        """
        plot the error with respect to the true solution on our optional
        visualization
        """
        myg = self.grids[self.nlevels-1].grid

        v = self.grids[self.nlevels-1].get_var("v")

        e = v - self.true_function(myg.x2d, myg.y2d)

        cmap = "viridis"

        plt.imshow(np.transpose(e[myg.ilo:myg.ihi+1, myg.jlo:myg.jhi+1]),
                   interpolation="nearest", origin="lower",
                   extent=[self.xmin, self.xmax, self.ymin, self.ymax], cmap=cmap)

        plt.xlabel("x")
        plt.ylabel("y")
        plt.title(r"current fine grid error")

        formatter = matplotlib.ticker.ScalarFormatter(useMathText=True)
        cb = plt.colorbar(format=formatter, shrink=0.5)

        cb.ax.yaxis.offsetText.set_fontsize("small")
        cl = plt.getp(cb.ax, 'ymajorticklabels')
        plt.setp(cl, fontsize="small")
Exemple #28
0
    def _cbar(cb, cmap, clim, vmin, under, vmax, over, title, ycb, fz_title,
              ticks, fz_ticks, outline, orientation, tcol):
        """Colorbar creation."""
        # ----------------- TITLE -----------------
        if title is not None:
            cb.set_label(title, labelpad=ycb, color=tcol,
                         fontsize=fz_title)

        # ----------------- TICKS -----------------
        if clim is not None:
            # Display only (min, max) :
            if ticks == 'minmax':
                ticks = [clim[0], clim[1]]
            # Display (min, vmin, vmax, max) :
            elif ticks == 'complete':
                ticks = [clim[0]]
                if vmin:
                    ticks.append(vmin)
                if vmax:
                    ticks.append(vmax)
                ticks.append(clim[1])
            # Use linearly spaced ticks :
            elif isinstance(ticks, (int, float)):
                ticks = np.arange(clim[0], clim[1] + ticks, ticks)
            # Set ticks and ticklabels :
            cb.set_ticks(ticks)
            cb.set_ticklabels(ticks)
            cb.ax.tick_params(labelsize=fz_ticks)
            # Change ticks color :
            tic = 'y' if (orientation == 'vertical') else 'x'
            cbytick_obj = plt.getp(cb.ax.axes, tic + 'ticklabels')
            plt.setp(cbytick_obj, color=tcol)

        # ----------------- OUTLINE -----------------
        cb.outline.set_visible(outline)
def save_ability_wins_distribution(statistics, ability_wins):

    fig = plt.figure()
    ax = fig.add_subplot(111)

    keys, wins = zip(*statistics) # pylint: disable=W0612

    data = [ability_wins[key] for key in keys]
    ax.boxplot(data)#, positions=[i for i in xrange(len(keys))])

    ax.set_xlim(0.5, len(statistics)+0.5)
    ax.set_ylim(0, TEST_BATTLES_NUMBER*len(HERO_LEVELS))

    locator = plt.IndexLocator(1, 0.5)
    formatter = plt.FixedFormatter([s[0] for s in statistics])

    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)
    plt.setp(plt.getp(ax, 'xticklabels'), rotation=45, fontsize=8, horizontalalignment='right')

    ax.set_title('wins destribution')

    plt.tight_layout()

    plt.savefig('/tmp/wins_destribution.png')
Exemple #30
0
def adding(T=50, plots=True):
    """The canonical "adding" test of long-range dependency learning for RNNs.

    :param int T: length of the test signal
    :param bool plots: display plots of trained output
    """

    # set up inputs
    N = 10000
    test_cut = int(N * 0.9)

    vals = np.random.uniform(0, 1, size=(N, T, 1)).astype(np.float32)
    mask = np.zeros((N, T, 1), dtype=np.float32)
    for m in mask:
        m[np.random.randint(T / 10)] = 1
        m[np.random.randint(T / 10, T / 2)] = 1
    inputs = np.concatenate((vals, mask), axis=-1)

    tmp = np.zeros_like(vals)
    tmp[mask.astype(np.bool)] = vals[mask.astype(np.bool)]

    targets = np.zeros((N, T, 1), dtype=np.float32)
    targets[:] = np.nan
    targets[:, -1] = np.sum(tmp, axis=1, dtype=np.float32)

    test = (inputs[test_cut:], targets[test_cut:])

    # build network
    optimizer = hf.opt.HessianFree(CG_iter=60, init_damping=20)
    rnn = hf.RNNet(
        shape=[2, 32, 64, 1],
        layers=[hf.nl.Linear(), hf.nl.ReLU(),
                hf.nl.Continuous(hf.nl.ReLU(), tau=20), hf.nl.ReLU()],
        W_init_params={"coeff": 0.25},
        loss_type=[hf.loss_funcs.SquaredError(),
                   hf.loss_funcs.StructuralDamping(1e-4, layers=[2],
                                                   optimizer=optimizer)],
        rec_layers=[2], use_GPU=True, debug=False,
        rng=np.random.RandomState(0))

    # scale spectral radius of recurrent weights
    W, _ = rnn.get_weights(rnn.W, (2, 2))
    W *= 1.0 / np.max(np.abs(np.linalg.eigvals(W)))

    rnn.run_epochs(inputs[:test_cut], targets[:test_cut],
                   optimizer=optimizer, minibatch_size=1024, test=test,
                   max_epochs=5, plotting=plots,
                   test_err=hf.loss_funcs.SquaredError())

    if plots:
        outputs = rnn.forward(inputs[:20])
        plt.figure()
        lines = plt.plot(outputs[-1][:].squeeze().T)
        plt.scatter(np.ones(outputs[-1].shape[0]) * outputs[-1].shape[1],
                    targets[:20, -1], c=[plt.getp(l, "color") for l in lines])
        plt.title("outputs")

        plt.show()
Exemple #31
0
def set_colorbar(fig, ax, im):

    cbar = fig.colorbar(im,
                        cax=ax.axCbar,
                        format=mpl.ticker.LogFormatterMathtext())

    # axes_obj = plt.getp(axCbar,'axes')
    ytl_obj = plt.getp(ax.axCbar, 'yticklabels')
    plt.setp(ytl_obj, fontsize=10)
    cbar.ax.set_ylabel('Occupancy', fontsize=10, rotation=270, labelpad=15)
Exemple #32
0
def test__EventCollection__set_prop():
    for prop, value, expected in [
        ('linestyle', 'dashed', [(0, (6.0, 6.0))]),
        ('linestyle', (0, (6., 6.)), [(0, (6.0, 6.0))]),
        ('linewidth', 5, 5),
    ]:
        splt, coll, _ = generate_EventCollection_plot()
        coll.set(**{prop: value})
        assert plt.getp(coll, prop) == expected
        splt.set_title(f'EventCollection: set_{prop}')
 def _plot_hu_bar(self):
     cax = self.axes.figure.add_axes([0.1, 0.1, 0.03, 0.8])
     cb = self.axes.figure.colorbar(self.axim_ctx, cax=cax)
     cb.set_label("HU", color=self.fg_color, fontsize=self.cb_fontsize)
     cb.outline.set_edgecolor(self.bg_color)
     cb.ax.yaxis.set_tick_params(color=self.fg_color)
     plt.setp(plt.getp(cb.ax.axes, 'yticklabels'), color=self.fg_color)
     cb.ax.yaxis.set_tick_params(color=self.fg_color,
                                 labelsize=self.cb_fontsize)
     self.hu_bar = cb
Exemple #34
0
    def _draw_colorbar(self):
        """ Draw a Matplotlib colorbar, save this figure without any boundary to a
    rendering buffer, and return this buffer as a numpy array.
    """
        dpi = get_dpi()
        # Compute the Matplotlib figsize: note the order of width, height.
        # The width is doubled because we will only keep the colorbar portion
        # before we export this image to buffer!
        figsize = (self.bar_size[1] / dpi * 2, self.bar_size[0] / dpi)

        # Convert cmap and clim to Matplotlib format.
        rgba = self.cmap.colors.rgba
        # Blend to white to avoid this Matplotlib rendering issue:
        # https://github.com/matplotlib/matplotlib/issues/1188
        for i in range(3):
            rgba[:, i] = (1 - rgba[:, -1]) + rgba[:, -1] * rgba[:, i]
        rgba[:, -1] = 1.
        if len(rgba) < 2:  # in special case of 'grays' cmap!
            rgba = np.array([[0, 0, 0, 1.], [1, 1, 1, 1.]])
        cmap = LinearSegmentedColormap.from_list('vispy_cmap', rgba)
        norm = mpl.colors.Normalize(vmin=self.clim[0], vmax=self.clim[1])
        sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)

        # Put the colorbar at proper location on the Matplotlib fig.
        fig = plt.figure(figsize=figsize, dpi=dpi)
        ax = plt.Axes(fig, [0, 0, 1, 1])
        ax.set_axis_off()
        fig.add_axes(ax)
        divider = make_axes_locatable(ax)
        cax = divider.append_axes('right', size='100%', pad=0.)
        cb = fig.colorbar(sm, cax=cax)
        ax.remove()

        # Apply styling to the colorbar.
        cb.set_label(self.label_str,
                     color=self.label_color,
                     fontsize=self.label_size)
        plt.setp(plt.getp(cb.ax.axes, 'yticklabels'),
                 color=self.label_color,
                 fontsize=self.tick_size)
        cb.ax.yaxis.set_tick_params(color=self.label_color)
        cb.outline.set_linewidth(self.border_width)
        cb.outline.set_edgecolor(self.border_color)

        # Export the rendering to a numpy array in the buffer.
        buf = io.BytesIO()
        fig.savefig(buf,
                    format='png',
                    bbox_inches='tight',
                    pad_inches=0,
                    dpi=dpi,
                    transparent=True)
        buf.seek(0)

        return plt.imread(buf)
Exemple #35
0
def spectroplot(Z,
                N,
                hop,
                fs,
                fdiv=None,
                tdiv=None,
                vmin=None,
                vmax=None,
                cmap=None,
                interpolation='none',
                colorbar=True):

    plt.imshow(20 * np.log10(np.abs(Z[:N // 2 + 1, :])),
               aspect='auto',
               origin='lower',
               vmin=vmin,
               vmax=vmax,
               cmap=cmap,
               interpolation=interpolation)

    # label y axis correctly
    plt.ylabel('Freq [Hz]')
    yticks = plt.getp(plt.gca(), 'yticks')
    plt.setp(plt.gca(), 'yticklabels', np.round(yticks / float(N) * fs))
    if (fdiv is not None):
        tick_lbls = np.arange(0, fs / 2, fdiv)
        tick_locs = tick_lbls * N / fs
        plt.yticks(tick_locs, tick_lbls)

    # label x axis correctly
    plt.xlabel('Time [s]')
    xticks = plt.getp(plt.gca(), 'xticks')
    plt.setp(plt.gca(), 'xticklabels', xticks / float(fs) * hop)
    if (tdiv is not None):
        unit = float(hop) / fs
        length = unit * Z.shape[1]
        tick_lbls = np.arange(0, int(length), tdiv)
        tick_locs = tick_lbls * fs / hop
        plt.xticks(tick_locs, tick_lbls)

    if colorbar is True:
        plt.colorbar(orientation='horizontal')
    def plotGraph(csvFile):
        #open dataframe obtained from LocalisedSynchrony.py
        #df = pd.read_csv("synchronyDataframe.csv")
        df = pd.read_csv(csvFile)
        print(df)
        #remove entries where synchrony values are zero
        df = df[df.SyncVal != 0]
        #df = df[df.SyncVal > 0.5]
        print(df)

        #create a list of channel number and its position in a grid
        channel_num = []
        for i in range(4096):
            channel_num.append(i)
        #print(channel_num)
        #list of grid co-ordinates
        coordinates = []
        x = 0
        y = 0

        for x in range(64):
            for y in range(64):
                coordinates.append((y, x))

        G = nx.from_pandas_edgelist(df, 'Ch_A', 'Ch_B', 'SyncVal')
        edges, weights = zip(*nx.get_edge_attributes(G, 'SyncVal').items())

        #pos = {0:(0,0),1:(0,1),2:(0,2),3:(0,4),4:(1,0),5:(1,1),6:(1,2),7:(1,3),8:(2,0),9:(2,1),10:(2,2),11:(2,3),12:(3,0),13:(3,1),14:(3,2),15:(3,3)}
        pos = dict(zip(channel_num, coordinates))

        #plot the network
        print("Weights: {}".format(weights))
        plt.title("Connectivity graph based on synchrony level")
        plt.xlabel("Channel(0-64)")
        plt.ylabel("Channel(0-64)")
        nx.draw(G,
                pos,
                with_labels=False,
                node_color='black',
                node_size=1,
                edgelist=edges,
                edge_color=weights,
                linewidths=2,
                font_size=6,
                grid=True,
                edge_cmap=plt.cm.jet)
        #nx.draw(G,pos, with_labels=False, node_color = 'blue', node_size = 10, linewidths = 1, font_size = 4,grid = True)

        plt.setp(plt.gca(), 'ylim', list(reversed(plt.getp(plt.gca(),
                                                           'ylim'))))

        plt.savefig("connectivity_{}.png".format(
            csvFile[:-4]))  #revoming the last 4 chars i.e. .csv
        plt.grid(True)
Exemple #37
0
def heatmap_generic(series, cmap='Greys', tone_color="k", title=None, vrange=None):

    # Instantiate figure
    fig, ax = plt.subplots(1, 1, figsize=(15, 5))

    # Load data and remove timezone from index
    series = series.to_frame()

    # Reshape data into time/day matrix
    ll = series.pivot_table(columns=series.index.date, index=series.index.time).values[::-1]

    # Plot data
    heatmap = ax.imshow(
        ll,
        extent=[mdates.date2num(series.index.min()), mdates.date2num(series.index.max()), 726449, 726450],
        aspect='auto',
        cmap=cmap,
        interpolation='none',
        vmin=vrange[0] if vrange is not None else None,
        vmax=vrange[-1] if vrange is not None else None,
    )

    # Axis formatting
    ax.xaxis_date()
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
    ax.yaxis_date()
    ax.yaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
    ax.invert_yaxis()
    ax.tick_params(labelleft=True, labelright=True, labelbottom=True)
    plt.setp(ax.get_xticklabels(), ha='left', color=tone_color)
    plt.setp(ax.get_yticklabels(), color=tone_color)

    # Spine formatting
    [ax.spines[spine].set_visible(False) for spine in ['top', 'bottom', 'left', 'right']]

    # Grid formatting
    ax.grid(b=True, which='major', color='white', linestyle=':', alpha=1)

    # Colorbar formatting
    cb = fig.colorbar(heatmap, orientation='horizontal', drawedges=False, fraction=0.05, aspect=100, pad=0.075)
    plt.setp(plt.getp(cb.ax.axes, 'xticklabels'), color=tone_color)
    cb.outline.set_visible(False)

    # Add title if provided
    if title is not None:
        plt.title(title, color=tone_color, y=1.01)

    # Tidy plot
    plt.tight_layout()

    # Return nil data to prevent auto-plotting in Jupyter notebooks
    plt.close()

    return fig
Exemple #38
0
 def focus(self):
     self.focus_off()
     for line in gl().lines:
         if plt.getp(line, "visible") is True:
             line._temp_hide = True
             plt.setp(line, "visible", False)
         else:
             line._temp_hide = False
     for line in self.lines:
         line._temp_hide = False
     self.show()
Exemple #39
0
def render_geo_field(data,
                     lats,
                     lons,
                     u=None,
                     v=None,
                     symm=False,
                     title='Test image',
                     cbar_label='SLP Anomalies [Pa]',
                     filename=None):

    plt.figure(figsize=(12, 10), dpi=300)
    lat_ndx = np.argsort(lats)
    lats = lats[lat_ndx]
    #data = data[::-1, :]
    m = Basemap(projection='merc',
                llcrnrlat=lats[0],
                urcrnrlat=lats[-1],
                llcrnrlon=lons[0],
                urcrnrlon=lons[-1],
                resolution='c')
    x, y = m(*np.meshgrid(lons, lats))
    mi = -47.  #np.min(data)
    ma = 18.  #np.max(data)
    if symm:
        if abs(ma) > abs(mi):
            mi = -ma
        else:
            ma = -mi
    step = (ma - mi) / 100
    levels = np.arange(mi, ma + step, step)
    cs = m.contourf(x, y, data, levels=levels)
    #if (u != None) & (v != None):
    #    q = m.quiver(x, y, u, v, width = 0.0015)
    #    qk = plt.quiverkey(q, -0.05, 1.1, 2, '$2 ms^{-1}$', coordinates = 'axes', labelpos = 'N')
    plt.clim(mi, ma)
    m.drawcoastlines(linewidth=1.5)
    m.drawmapboundary()
    #m.drawparallels(np.arange(lats[0], lats[-1]+1, 10), dashes = [1,3], labels = [0,0,0,0], color = (.2, .2, .2),
    #fontsize = 8.5)
    #m.drawmeridians(np.arange(lons[0], lons[-1]+1, 10), dashes = [1,3], labels = [0,0,0,0], color = (.2, .2, .2),
    #fontsize = 8.5)
    plt.title(title)
    cbar = plt.colorbar(format=r"%2.2f",
                        shrink=0.75,
                        ticks=np.arange(mi, ma + step, (ma - mi) / 8),
                        aspect=25,
                        drawedges=False)
    cbar.set_label(cbar_label)
    cbar_obj = plt.getp(cbar.ax.axes, 'yticklabels')
    plt.setp(cbar_obj, fontsize=10, color=(.1, .1, .1))
    if filename != None:
        plt.savefig(filename)
    else:
        plt.show()
Exemple #40
0
def black_colorbar(colorbar, bg_color='black', fg_color='white'):

    # Ref: https://stackoverflow.com/questions/9662995/matplotlib-change-title-and-colorbar-text-and-tick-colors?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
    # Label and label color
    #colorbar.set_label('colorbar label', color=fg_color)
    # Edge color
    colorbar.outline.set_edgecolor(fg_color)
    # Tick color
    colorbar.ax.yaxis.set_tick_params(color=fg_color)
    # Tick label color
    plt.setp(plt.getp(colorbar.ax.axes, 'yticklabels'), color=fg_color)
def stem_plot(sensor1, sensor2, gestureName):
    gestureName += ".pdf"
    markerline, stemlines, baseline = plt.stem(sensor1,
                                               markerfmt='o',
                                               label='Sensor 1')
    plt.setp(stemlines, 'color', plt.getp(markerline, 'color'))
    plt.setp(stemlines, 'linestyle', 'dotted')

    markerline, stemlines, baseline = plt.stem(sensor2,
                                               markerfmt='o',
                                               label='Sensor 2')
    plt.setp(stemlines, 'color', plt.getp(markerline, 'color'))
    plt.setp(stemlines, 'linestyle', 'dotted')

    plt.legend(bbox_to_anchor=(0., 1.02, 1., .102),
               loc='lower left',
               ncol=2,
               mode="expand",
               borderaxespad=0.)
    #plt.show()
    plt.savefig(gestureName, bbox_inches='tight')
Exemple #42
0
def plot_template_length_distribution(model, ax, plt):
    ax.plot(model['tlen'] / model['tlen'].max())
    ax.text(len(model['tlen']),
            plt.getp(ax, 'ylim')[1],
            'n={}'.format(model['tlen'].sum()),
            ha='right',
            va='top')
    plt.setp(ax,
             xlabel='Template length (bp)',
             ylim=(0, 1.2),
             yticks=[],
             title='Template length distribution')
Exemple #43
0
def prob_2a(X_train, y_train, X_test, y_test):
    n, d = X_train.shape
    indicator = []
    for i in range(d):
        if i < 54:
            indicator.append(1)
        else:
            indicator.append(2)
    indicator = np.array(indicator)
    indicator
    model = NaiveBayes()
    fit1 = model.fit(X_train, y_train, indicator)
    y_pred = model.predict(X_test)
    print 'Confusion Matrix for naive bayes classifier: ', ConfusionMatrix(
        y_pred, y_test)
    print 'accuracy:', accuracy(y_pred, y_test)
    #len(model.theta0[0:54])
    x = range(1, 55)
    markerline, stemlines, baseline = plt.stem(x,
                                               model.theta0[0:54],
                                               markerfmt='o',
                                               label='theta_1 for y=0')
    plt.setp(stemlines, 'color', plt.getp(markerline, 'color'))
    plt.setp(stemlines, 'linestyle', 'dotted')

    markerline, stemlines, baseline = plt.stem(x,
                                               model.theta1[0:54],
                                               markerfmt='o',
                                               label='theta_1 for y=1')
    plt.setp(stemlines, 'color', plt.getp(markerline, 'color'))
    plt.setp(stemlines, 'linestyle', 'dotted')

    #plt.legend()
    #plt.show()

    plt.legend()
    print '...saving plot from problem 2 (b) as prob2b.png'
    plt.savefig('prob2b.png')
    plt.show()
    plt.close()
Exemple #44
0
    def setupGrid(self,
                  thickness=1.0,
                  style='--',
                  startx=0.0,
                  deltax=0.1,
                  endx=1.0,
                  starty=0.0,
                  deltay=0.1,
                  endy=1.0):

        ax = self.getAxes()
        xticklines = plt.getp(ax, 'xticklines')
        yticklines = plt.getp(ax, 'yticklines')
        xgridlines = plt.getp(ax, 'xgridlines')
        ygridlines = plt.getp(ax, 'ygridlines')
        xticklabels = plt.getp(ax, 'xticklabels')
        yticklabels = plt.getp(ax, 'yticklabels')

        plt.setp(xticklines, 'linewidth', thickness)
        plt.setp(yticklines, 'linewidth', thickness)
        plt.setp(xgridlines, 'linestyle', style)
        plt.setp(ygridlines, 'linestyle', style)
        plt.setp(yticklabels, 'color', 'k', fontsize='medium')
        plt.setp(xticklabels, 'color', 'k', fontsize='medium')
        ax.set_xticks(np.arange(startx, endx, deltax))
        ax.set_yticks(np.arange(starty, endy, deltay))

        ax.xaxis.grid(linewidth=thickness)
        ax.yaxis.grid(linewidth=thickness)
        plt.grid(True)
def save_ability_mathces_statistics(statistics, matches):  # pylint: disable=R0914
    fig = plt.figure()
    ax = fig.add_subplot(111)

    keys, wins = list(zip(*statistics))  # pylint: disable=W0612

    index = dict((key, i) for i, key in enumerate(keys))

    data = []
    for (x, y), (w_1, w_2) in list(matches.items()):
        data.append((index[x], index[y], 1000 * w_1 / float(w_1 + w_2)))
        data.append((index[y], index[x], 1000 * w_2 / float(w_1 + w_2)))

    x, y, powers = list(zip(*data))

    ax.scatter(x, y, s=powers, marker='o', c=powers)

    ax.set_xlim(-0.5, len(statistics) + 0.5)
    ax.set_ylim(-0.5, len(statistics) + 0.5)

    locator = plt.IndexLocator(1, 0)
    formatter = plt.FixedFormatter([s[0] for s in statistics])

    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)
    plt.setp(plt.getp(ax, 'xticklabels'),
             rotation=45,
             fontsize=8,
             horizontalalignment='right')

    ax.yaxis.set_major_locator(locator)
    ax.yaxis.set_major_formatter(formatter)
    plt.setp(plt.getp(ax, 'yticklabels'), fontsize=8)

    ax.set_title('matches results')

    plt.tight_layout()

    plt.savefig('/tmp/matches.png')
Exemple #46
0
def plotRegions(startTimes, endTimes, vmin=0, vmax=1, labels=None):
    nbRegions = startTimes.size
    for n in range(nbRegions):
        line = plt.plot([startTimes[n], startTimes[n]],
                        [vmin, vmax], '-')
        plt.plot([endTimes[n], endTimes[n]],
                 [vmin, vmax], '-', color=plt.getp(line[0], 'color'))
        ## plt.plot([startTimes[n], startTimes[n]],
        ##          [vmin, vmax], 'g-')
        ## plt.plot([endTimes[n], endTimes[n]],
        ##          [vmin, vmax], 'y-')
        if labels != None:
            plt.text((startTimes[n]+endTimes[n])/2.0,
                     vmax - (- vmin + vmax) * 1.0 / 10.0 - \
                     (-vmin+vmax) * 8.0 / 10.0 / (nbRegions-1.0) * n,
                     labels[n],
                     color='w',
                     horizontalalignment='center',
                     verticalalignment='center',
                     fontsize=16,
                     weight='extra bold',
                     backgroundcolor=plt.getp(line[0], 'color'))
Exemple #47
0
 def toggleLockCmap(self):
     if self.ui.checkBox_lockcmap.isChecked():
         self.clim1 = plt.getp(plt.getp(self.slice1, 'images')[0], 'clim')
         self.clim2 = plt.getp(plt.getp(self.slice2, 'images')[0], 'clim')
         self.clim3 = plt.getp(plt.getp(self.slice3, 'images')[0], 'clim')
         self.lockColormap = True
     else:
         self.lockColormap = False
    def new_attributes(self, obj, attr_dict, overwrite=False):
        '''
        Finds the differences of the plot attributes between this iteration and the previous iterations. All differences are stored as dictionaries in the history variable.
        Makes sure that all changes are stored correctly and plot attributes are not overwritten if not explicitly defined.
        '''
        prev_changes = self.history[self.iter - 1]
        next_changes = self.history[self.iter]

        prev, next = {}, {}

        if not overwrite or obj not in prev_changes:
            for key, value in attr_dict.items():

                value = self.get_nested_np_color(value)
                old_value = self.get_nested_np_color(plt.getp(obj, key))

                if old_value != value:
                    prev[key] = old_value
                    next[key] = value
        else:
            old_dict = prev_changes[obj]
            for key, value in attr_dict.items():
                value = self.get_nested_np_color(value)
                old_value = old_dict[
                    key] if key in old_dict else self.get_nested_np_color(
                        plt.getp(obj, key))
                if old_value != value:
                    prev[key] = old_value
                    next[key] = value
        if prev:
            if overwrite or obj not in prev_changes:
                prev_changes[obj] = prev
            else:
                prev_changes[obj].update(prev)

        if next:
            next_changes[obj] = next
            self.change_attributes(obj, next)
Exemple #49
0
    def add_colorbar(self) -> None:
        """Draw color bar to indicate the impedance value."""
        # self.cax = self.figure.add_axes([0.1, 0.1, 0.8, 0.05])
        norm = matplotlib.colors.Normalize(vmin=0, vmax=15)

        sm = cm.ScalarMappable(cmap=self.cmap, norm=norm)
        cbr = pyplot.colorbar(sm, cax=self.cax, orientation="horizontal")
        pyplot.setp(pyplot.getp(cbr.ax.axes, 'xticklabels'),
                    color=os.environ.get('QTMATERIAL_SECONDARYTEXTCOLOR',
                                         '#000000'),
                    size=10)
        ticks = [0, 5, 10, 15]
        cbr.set_ticks(ticks)
        cbr.set_ticklabels([f'{i} k$\Omega$' for i in ticks])
Exemple #50
0
 def toggle_aux(self):
     """turn aux data on and off"""
     try:
         alpha = plt.getp(self.ax1.cathode_line[0], "alpha")
         if alpha:
             self.ax1.cathode_line[0].set_alpha(0)
             self.ax1.anode_line[0].set_alpha(0)
         else:
             self.ax1.cathode_line[0].set_alpha(1)
             self.ax1.anode_line[0].set_alpha(1)
         self.figure.canvas.draw_idle()
     except Exception as e:
         print(e)
         pass
Exemple #51
0
def bootstrap_plot(xpts, bootstrap_curves, CI=95, line_kws={}, fill_kws={}):
    c_lower = np.percentile(bootstrap_curves, (100 - CI) / 2, axis=0)
    c_median = np.percentile(bootstrap_curves, 50, axis=0)
    c_upper = np.percentile(bootstrap_curves, (100 + CI) / 2, axis=0)

    # Additional keyword arguments to plot or fill_between can be passed as a dictionary via line_kws and fill_kws, respectively
    med = plt.plot(xpts, c_median, **line_kws)
    if 'alpha' not in fill_kws.keys(): fill_kws['alpha'] = 0.25
    ci = plt.fill_between(xpts,
                          c_upper,
                          c_lower,
                          color=plt.getp(med[0], 'color'),
                          **fill_kws)
    return med, ci
def Save_Frame(i, Data, Fname, SkipFactor):

    Audio = np.concatenate((Data["audioin"][0:(i * SkipFactor)],
                            np.zeros(len(Data["t"]) - (i * SkipFactor))))
    in1 = np.concatenate((Data["nIn1"][0:(i * SkipFactor)],
                          np.zeros(len(Data["t"]) - (i * SkipFactor))))
    in2 = np.concatenate((Data["nIn2"][0:(i * SkipFactor)],
                          np.zeros(len(Data["t"]) - (i * SkipFactor))))
    p1 = np.concatenate((Data["pred1"][0:(i * SkipFactor)],
                         np.zeros(len(Data["t"]) - (i * SkipFactor))))
    p2 = np.concatenate((Data["pred2"][0:(i * SkipFactor)],
                         np.zeros(len(Data["t"]) - (i * SkipFactor))))

    HM_Data = np.array(
        [[Data["W1_1"][i * SkipFactor], Data["W1_2"][i * SkipFactor]],
         [Data["W2_1"][i * SkipFactor], Data["W2_2"][i * SkipFactor]],
         [Data["W3_1"][i * SkipFactor], Data["W3_2"][i * SkipFactor]],
         [Data["W4_1"][i * SkipFactor], Data["W4_2"][i * SkipFactor]],
         [Data["W5_1"][i * SkipFactor], Data["W5_2"][i * SkipFactor]],
         [Data["W6_1"][i * SkipFactor], Data["W6_2"][i * SkipFactor]],
         [Data["W7_1"][i * SkipFactor], Data["W7_2"][i * SkipFactor]],
         [Data["W8_1"][i * SkipFactor], Data["W8_2"][i * SkipFactor]]])

    # plot it
    f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [4, 1]})

    sns.heatmap(HM_Data, vmin=0, vmax=1.1, cmap=sns.cm.rocket_r, ax=a1)

    plt.setp(plt.getp(a1, 'xticklabels'), color='w')

    a0.set_xlim((0, 16.5))
    a0.set_ylim((-1, 11))
    a0.set_xlabel('Time (s)')
    a0.set_ylabel('Voltage (V)')

    a0.plot(Data["t"], Audio, lw=2, label='Audio')
    a0.plot(Data["t"], in1, lw=2, label='Post-Neuron 1 Input')
    a0.plot(Data["t"], in2, lw=2, label='Post-Neuron 2 Input')
    a0.plot(Data["t"], p1, lw=2, label='Prediction 1')
    a0.plot(Data["t"], p2, lw=2, label='Prediction 2')

    a0.legend(loc='upper right')

    f.tight_layout()
    f.savefig("Visualizations/{}/Frames/frame{}.png".format(Fname, str(i)),
              dpi=300)

    plt.close(f)
    return
Exemple #53
0
def main(params):
    reference_space = mcc.get_reference_space()
    structure_vals, n = get_mean_value_per_structure('297',
                                                     dat.structure_id.unique())
    rgb_vals, n = get_cmap('297', scale=0.0001)
    image = [0, 0, 0]
    image[0] = reference_space.get_slice_image(0, params['xcoord'],
                                               rgb_vals)  #posterior
    image[1] = np.flip(
        np.rot90(reference_space.get_slice_image(2, params['zcoord'],
                                                 rgb_vals)), 0)  #right
    image[2] = np.rot90(
        reference_space.get_slice_image(1, params['ycoord'],
                                        rgb_vals))  #inferior
    fig = plt.figure(figsize=(8, 3), facecolor=rgb_vals[0])
    columns = 3
    rows = 1
    for i in range(columns * rows):
        fig.add_subplot(rows, columns, i + 1)
        f = plt.imshow(image[i], cmap=cm.BuPu)
        plt.axis('off')
    cbar = fig.colorbar(f, fraction=0.046)
    cbar.set_label('pTau Probability (per mm$\mathregular{^{3}}$)',
                   rotation=90,
                   color='w',
                   fontsize=12)
    plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='w', fontsize=10)

    maxval = max(structure_vals.items(), key=operator.itemgetter(1))[1]
    cbar.ax.set_yticklabels([
        0,
        np.round(maxval * .2, 2),
        np.round(maxval * .4, 2),
        np.round(maxval * .6, 2),
        np.round(maxval * .8, 2),
        np.round(maxval, 2)
    ])
    if not os.path.exists(params['savepath']):
        os.mkdir(params['savepath'])
    mouse_line_fname = '297'
    plt.savefig(os.path.join(
        params['savepath'],
        '{0}_map_{1}-{2}-{3}.png'.format(mouse_line_fname, params['xcoord'],
                                         params['zcoord'], params['ycoord'])),
                facecolor=fig.get_facecolor(),
                bbox_inches='tight',
                pad_inches=0.3,
                format='png',
                dpi=300)
def main(params):
    reference_space =  mcc.get_reference_space()
    
    structure_vals, n = get_mean_value_per_structure(params['mouse_line'], 
                                                     params['age'], 
                                                     dat.structure_id.unique())
    rgb_vals, n = get_cmap(params['mouse_line'], params['age'], params['scale'])
    image = [0,0,0]
    image[0] = reference_space.get_slice_image(0, params['xcoord'], rgb_vals) #posterior
    image[1] = np.flip(np.rot90(reference_space.get_slice_image(2, params['zcoord'], rgb_vals)), 0) #right
    image[2] = np.rot90(reference_space.get_slice_image(1, params['ycoord'], rgb_vals))   #inferior
    fig = plt.figure(figsize=(8, 3), facecolor=rgb_vals[0])
    columns = 3
    rows = 1
    for i in range(columns*rows):
        fig.add_subplot(rows, columns, i+1)
        f = plt.imshow(image[i], cmap = cm.hot)
        plt.axis('off')
    cbar = fig.colorbar(f, fraction=0.046)
    cbar.set_label('Plaque % Volume', rotation=90, color = 'w', fontsize = 12)
    plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='w', fontsize = 10)
    
    maxval = max(structure_vals.items(), key=operator.itemgetter(1))[1]
    cbar.ax.set_yticklabels([0, 
                             np.round(maxval*.125, 2), 
                             np.round(maxval*.25, 2), 
                             np.round(maxval*.375, 2),
                             np.round(maxval*.5, 2), 
                             np.round(maxval*.625, 2),
                             np.round(maxval*.75, 2),
                             np.round(maxval*.875, 2),
                             np.round(maxval, 2)])
    if not os.path.exists(params['savepath']):
        os.mkdir(params['savepath'])
    if params['mouse_line'] == 'APP/PS1':
        mouse_line_fname = 'APP_PS1'
    else:
        mouse_line_fname = params['mouse_line']
    plt.savefig(os.path.join(params['savepath'], 
                             '{0}_{1}_map_{2}-{3}-{4}.png'.format(mouse_line_fname,
                             params['age'],
                             params['xcoord'],
                             params['zcoord'],
                             params['ycoord'])), 
            facecolor=fig.get_facecolor(),
            bbox_inches='tight', 
            pad_inches=0.3, 
            format='png', 
            dpi=1000)
Exemple #55
0
def _plot_topo(info=None, times=None, show_func=None, layout=None,
               decim=None, vmin=None, vmax=None, ylim=None, colorbar=None,
               border='none', axis_facecolor='k', fig_facecolor='k',
               cmap='RdBu_r', layout_scale=None, title=None, x_label=None,
               y_label=None, vline=None, font_color='w'):
    """Helper function to plot on sensor layout"""
    import matplotlib.pyplot as plt

    # prepare callbacks
    tmin, tmax = times[[0, -1]]
    on_pick = partial(show_func, tmin=tmin, tmax=tmax, vmin=vmin,
                      vmax=vmax, ylim=ylim, x_label=x_label,
                      y_label=y_label, colorbar=colorbar)

    fig = plt.figure()
    if colorbar:
        norm = normalize_colors(vmin=vmin, vmax=vmax)
        sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
        sm.set_array(np.linspace(vmin, vmax))
        ax = plt.axes([0.015, 0.025, 1.05, .8], axisbg=fig_facecolor)
        cb = fig.colorbar(sm, ax=ax)
        cb_yticks = plt.getp(cb.ax.axes, 'yticklabels')
        plt.setp(cb_yticks, color=font_color)
        ax.axis('off')

    my_topo_plot = iter_topography(info, layout=layout, on_pick=on_pick,
                                   fig=fig, layout_scale=layout_scale,
                                   axis_spinecolor=border,
                                   axis_facecolor=axis_facecolor,
                                   fig_facecolor=fig_facecolor,
                                   colorbar=colorbar)

    for ax, ch_idx in my_topo_plot:
        if layout.kind == 'Vectorview-all' and ylim is not None:
            this_type = {'mag': 0, 'grad': 1}[channel_type(info, ch_idx)]
            ylim_ = [v[this_type] if _check_vlim(v) else v for v in ylim]
        else:
            ylim_ = ylim

        show_func(ax, ch_idx, tmin=tmin, tmax=tmax, vmin=vmin,
                  vmax=vmax, ylim=ylim_)

        if ylim_ and not any(v is None for v in ylim_):
            plt.ylim(*ylim_)

    if title is not None:
        plt.figtext(0.03, 0.9, title, color=font_color, fontsize=19)

    return fig
Exemple #56
0
    def render(self, date, mode='web'):
        elevations = self._compute_elevations(date)
        """ Create the plot """
        self.figure = plt.figure(figsize=(8.485, 6))
        self.figure.subplots_adjust(0.03,
                                    0.00,
                                    0.97,
                                    0.95,
                                    hspace=0.0,
                                    wspace=0.0)

        # Show earth with Mercator projection
        ax = Basemap(projection='merc',
                     llcrnrlon=self.lon1,
                     llcrnrlat=self.lat1,
                     urcrnrlon=self.lon2,
                     urcrnrlat=self.lat2,
                     resolution="c",
                     fix_aspect=False)
        ax.drawcoastlines()

        if mode == 'pub':
            cdict = {
                'red': ((0., .75, .75), (1., 0.05, 0.05)),
                'green': ((0., .75, .75), (1., 0.05, 0.05)),
                'blue': ((0., .75, .75), (1., 0.05, 0.05))
            }
        else:
            cdict = {
                'red': ((0., 1., 1.), (1., .0, 0.)),
                'green': ((0., 1., 1.), (1., 1., 1.)),
                'blue': ((0., 0., 0.), (1., 0., 0.))
            }

        my_cmap = mpl.colors.LinearSegmentedColormap('my_colormap', cdict,
                                                     1024)
        im = ax.imshow(elevations, cmap=my_cmap, vmin=0, vmax=90)

        cb = self.figure.colorbar(im,
                                  orientation='horizontal',
                                  pad=0.02,
                                  shrink=0.95,
                                  ticks=[0, 30, 60, 90],
                                  aspect=50,
                                  format=u'%.0f\N{DEGREE SIGN}')
        cb.ax.set_xlabel('Elevation above the horizon (when dark)',
                         fontsize=18)
        cl = plt.getp(cb.ax, 'xmajorticklabels')
        plt.setp(cl, fontsize=16)
Exemple #57
0
def _set_style(fig, ax, pp, style):
    "Sets the colorscheme for figure, axis and plot object (`pp`) according to style"
    # check if ax is 'normal' or cartopy projection
    is_geoax = False
    if isinstance(ax, geoaxes.GeoAxesSubplot):
        is_geoax = True

    # parse styles
    style_dict = _style_dict(style)
    supported_styles = list(_style_dict_raw().keys())
    if (style not in supported_styles) and (style is not None):
        raise ValueError("Given value for `style`(%s) not supported. \
        Currently support [%s]" % (style, supported_styles))
    # can I declare these in an automated fashinon?
    bgcolor = style_dict.pop("bgcolor", None)
    fgcolor = style_dict.pop("fgcolor", None)
    blend_outline_patch = style_dict.pop("blend_outline_patch", None)

    fig.patch.set_facecolor(bgcolor)
    if is_geoax:
        ax.background_patch.set_facecolor(bgcolor)
    else:
        ax.set_facecolor(bgcolor)

    # Use the boundary to blend the edges of the globe into background
    if blend_outline_patch:
        if is_geoax:
            ax.outline_patch.set_edgecolor(bgcolor)
            ax.outline_patch.set_antialiased(True)
            ax.outline_patch.set_linewidth(2)

    # modify colorbar
    try:
        cb = pp.colorbar
    except (AttributeError):
        cb = None

    if cb is not None:
        # set colorbar label plus label color
        cb.set_label(cb.ax.axes.get_ylabel(), color=fgcolor)

        # set colorbar tick color
        cb.ax.yaxis.set_tick_params(color=fgcolor)

        # set colorbar edgecolor
        cb.outline.set_edgecolor(fgcolor)

        # set colorbar ticklabels
        plt.setp(plt.getp(cb.ax.axes, "yticklabels"), color=fgcolor)
Exemple #58
0
def word_cloud(df, top=25, figsize=(15,15), cloud_width=800, cloud_height=400, cloud_font='fonts/ANefelAdeti.ttf', cloud_label=1):
    def top_features(df, top):
        _features = df.mean(axis=0)
        _features = _features[_features > 0]
        if _features.shape[0] < top:
            _features = _features.to_frame().reset_index()
        else:
            _features = _features.head(top).to_frame().reset_index()
        _features.columns = ['feature', 'score']
        return _features

    df = top_features(df, top)
    wordcloud = WordCloud(font_path=cloud_font, mode='RGB', width=cloud_width, height=cloud_height)
    terms = [bidialg.get_display(arabic_reshaper.reshape(term)) for term in df['feature']]

    features = pd.Series(df['score'].values, index=terms).to_dict()
    wordcloud.generate_from_frequencies(frequencies=features)
    plt.figure(figsize=figsize, facecolor='k')
    plt.imshow(wordcloud)
    title = plt.title('Lable: ' + str(cloud_label))
    plt.getp(title)
    plt.getp(title, 'text')
    plt.setp(title, color='w')
    plt.axis("off")
Exemple #59
0
 def plot_bar(self, data, **kwargs):
     """
     Plots bar based on passed data
     """
     cb = colorbar(data, cax=self)
     cb.set_label(self.label,
                  color=self.fg_color,
                  fontsize=self.cb_fontsize)
     cb.outline.set_edgecolor(self.bg_color)
     cb.ax.yaxis.set_tick_params(color=self.fg_color)
     cb.ax.yaxis.set_label_position('left')
     plt.setp(plt.getp(cb.ax.axes, 'yticklabels'), color=self.fg_color)
     cb.ax.yaxis.set_tick_params(color=self.fg_color,
                                 labelsize=self.cb_fontsize)
     self.bar = cb
 def export_matlab_script(self, filename):
     with open(filename, 'w') as file:
         for figure in self:
             print('% Generated by WaveSyn.',
                   'figure;',
                   sep='\n',
                   file=file)
             for line in figure.line_objects:
                 line0 = line[0]
                 func = "polarplot" if figure.is_polar else "plot"
                 xdata = pyplot.getp(line0, "xdata")
                 ydata = pyplot.getp(line0, "ydata")
                 color = pyplot.getp(line0, "color")
                 linewidth = pyplot.getp(line0, "linewidth")
                 linestyle = pyplot.getp(line0, "linestyle")
                 linespec = {
                     "Color": color,
                     "LineWidth": linewidth,
                     "LineStyle": linestyle
                 }
                 print(codegen.commonplot(xdata, ydata, linespec,
                                          func=func),
                       file=file)
                 print("hold on", file=file)