コード例 #1
0
ファイル: x64plots.py プロジェクト: gopastro/pyphamas
 def plot_histogram(self, bf, row, col, plot_sigma=True,
                    hold=False):
     self.bf = bf
     if self.bf is None:
         raise Exception("Need to pass in a BinFile instance to plot object")
     if not hasattr(self.bf, 'data_out'):
         raise Exception("BinFile instance does not have any data.")
     if not hold:
         self.clear()
         self.lines = []
     try:
         h = self.bf.data_out[row, col, :, :].real.flatten()
     except:
         print "Error in extracting histogram"
     if hasattr(self.bf, 'pixel_label'):
         label="Row%d, Col%d (Pix: %s)" % (self.bf.row_start+row, self.bf.col_start+col, self.bf.pixel_label.get((row, col), 'NC'))
     else:
         label="Row%d, Col%d" % (self.bf.row_start+row, self.bf.col_start+col)
     self.hist(h, bins=20, label=label)
     if MATPLOTLIBV1_0:
         datacursor()
     self.set_subplot_title("%s" % self.bf.basename)
     if plot_sigma:
         y1, y2 = self.get_ylims()
         for x in (-8, 8):
             self.plot([x, x], [y1, y2], 'r--', linewidth=2, 
                       label="_nolegend_")
     self.set_xlim(-64, 64)
     self.set_legend(loc='best')
コード例 #2
0
def Graph_Instant_boot():
    print ('inside Graph_Instant_boot graph')
    Plot1 = np.loadtxt('Output_VHFS_Instant_boot.txt')
    Plot2 = np.loadtxt('Output_VHFS_Instant_boot_2.txt')
    fig = plt.figure()
    #pl.subplot(311)
    
    pl.title('Instant_Boot: VHFS1 vs VHFS2')    
    pl.xlabel('Incrementals')
    pl.ylabel('Time Taken in secs')
    pl.xlim(-1,11)
    
    x = Plot1[:,0]
    y = Plot1[:,1]
    y2 = Plot2[:,1]
    #yerr = Plot1[:,4]
    #xticks = Plot1[:,1]
    #plt.xticks(xticks)
    #plt.xscale('log')
    #plt.yscale('log')
    #plt.xticks(xticks)
    #pl.errorbar(x,y,yerr,ecolor='b')
    pl.plot(x,y, 'b', label = 'VHFS1', marker = 'o')
    pl.plot(x,y2, 'y', label = 'VHFS2', marker = 'o')
    pl.legend(loc = 'upper right', numpoints = 1)
    datacursor(display='multiple', draggable=True)
    #pl.show()
 
    pl.savefig('Instant_boot_VHFS_vs_VHD.ps')
    pl.savefig('Instant_boot_VHFS_vs_VHD.png')
    pl.savefig('Instant_boot_VHFS_vs_VHD.pdf')
    print ('endddd')
    
    plt.close(fig)
コード例 #3
0
ファイル: NISTASD.py プロジェクト: atronchi/NISTASD
    def plot(self):
        specs = pl.array( list(set([ l['spec'] for l in self.lines ])) )
        specs.sort()
        self.specs = specs

        pl.figure()
        pl.hold('on')
        pl.grid('on')
        pl.jet()

        lines = [] 
        lines_spec = list(pl.zeros(len(specs)))
        for i in range(0,len(self.lines)):
            ispc = pl.find( specs == self.lines[i]['spec'] )
            self.colr = pl.cm.get_cmap()( float(ispc)/len(specs) )
            wl = self.lines[i]['wave']
            ri = float(self.lines[i]['rel_int'])
            lines.append( pl.plot( [wl, wl], [0., ri if not isnan(ri) else 0.], '.-', color=self.colr )[0] )
            lines_spec[ispc] = lines[-1]
        datacursor(lines,formatter='x={x:8.3f}\ny={y:8.3f}'.format)

        pl.rc('text',usetex=True)
        pl.xlabel('$\lambda ~ [\AA]$')
        pl.ylabel('relative intensity [arb]')
        pl.title('Spectrum for '+self.spec+' from NIST ASD')

        if len(specs) > 1:
            pl.legend( lines_spec,specs )

        pl.show()
コード例 #4
0
ファイル: plotting.py プロジェクト: chan-y-park/mose
def plot_k_walls(k_walls, plot_range=None,
                 plot_data_points=False,):
    """
    Plot K-walls for debugging purpose.
    """
    pyplot.figure()
    pyplot.axes().set_aspect('equal')

    for k_wall in k_walls:
        xs = k_wall.get_xs() 
        ys = k_wall.get_ys() 
        pyplot.plot(xs, ys, '-', label=k_wall.identifier)

        if(plot_data_points == True):
            pyplot.plot(xs, ys, 'o', color='k', markersize=4)

    if plot_range is None:
        pyplot.autoscale(enable=True, axis='both', tight=None)
    else:
        [[x_min, x_max], [y_min, y_max]] = plot_range
        pyplot.xlim(x_min, x_max)
        pyplot.ylim(y_min, y_max)

    mpldatacursor.datacursor(
        formatter='{label}'.format,
        hover=True,
    )

    pyplot.show()
コード例 #5
0
    def measure_iv(self):
        self.get_vd_values()
        self.textBrowser.append('Measuring I-V from ' + str(self.vd_start) +
                                'V to ' + str(self.vd_stop) + ' V')
        vd_values = np.linspace(self.vd_start, self.vd_stop, num=self.vd_steps,
                                endpoint=True)
        id_values = np.zeros_like(vd_values)
#        self.measure_current()
        for i, vd in np.ndenumerate(vd_values):
            self.set_voltage_vd(vd)
            id_values[i] = self.measure_current()
            if self.stop_engaged:
                print('stop')
                self.stop_engaged = False
                break

            self.update_progress((i[0] + 1.0)/self.vd_steps)
        self.set_voltage_vd(0)
        self.textBrowser.append('Measurement completed')
        data = pd.DataFrame({'Voltage': vd_values, 'Current': id_values})
        data.set_index('Voltage', inplace=True)
        self.data_iv = data
        data.to_csv('measurement_iv.csv')
        data.to_msgpack('measurement_iv.msgpack')
        ax = data.plot()
        datacursor(ax)
#        datacursor(display='single', draggable=True)
        winsound.Beep(750, 1000)
        fig = ax.get_figure()
        fig.savefig('measurement_iv.png')
        plt.show()
コード例 #6
0
ファイル: herajupyter.py プロジェクト: HERA-Team/herajupyter
def exploredata1d(data, slider='chans', stack='ants'):
    """ Set up interactive 1d (line) plotting for vis data of dimension (ints, ants, chans). """
    
    axdict = {'ints': 0, 'ants': 1, 'chans': 2}
    assert slider in axdict.keys() and stack in axdict.keys(), 'slider or stack param not allowed'

    slax = axdict[slider]
    # need to account for axis shift after first 'take'
    stax = axdict[stack] if axdict[stack] <= slax else axdict[stack] - 1
    slmax = data.shape[axdict[slider]]
    stmax = data.shape[axdict[stack]]

    xaxis = [name for name in axdict.keys() if name != slider and name != stack][0]
    
    fcndict = {'Real': np.real, 'Imag': np.imag, 'Amp': np.abs, 'Phase': np.angle}

    @interact(sl=(0, slmax, 1), f=['Real', 'Imag', 'Amp', 'Phase'])
    def plotautos(sl, f):
        pl.figure(figsize=(15,8))
        pl.clf()
        pl.xlabel(xaxis)
        pl.ylabel(f)
        
        fcn =  fcndict[f]
        
        for st in range(stmax):
            pl.plot(fcn(data.take(sl, axis=slax).take(st, axis=stax)), label='{0} {1}'.format(stack.rstrip('s'), st))
            
        print('Plotting {0} vs. {1}.'.format(f, xaxis))
        print('Slider for {0}. A line per {1}.'.format(slider, stack.rstrip('s')))
        print('Click on a line to see {0} number'.format(stack.rstrip('s')))
    datacursor(formatter='{label}'.format)
def main(icorr_mean_list):
    suffix = rate2suffix(icorr_mean_list)
    # load data
    datapath = os.path.join(os.path.abspath('./'), 'data')
    filename = 'popdata_'+suffix+'.npz'
    datafile = os.path.join(datapath,filename)
    if os.path.isfile(datafile) is False:
        print 'no data available, execute Life_Cycle_Optimization.py with \
                icorr_mean_list={} fist'.format(icorr_mean_list)
        sys.exit(1)
    else:
        popdata = np.load(datafile)
        allpop = popdata['allpop']
        allfits = popdata['allfits']
        front = popdata['front']
        frontfits = popdata['frontfits']
        pop = popdata['pop']
        popfits = popdata['popfits']

    plt.ion()
    plt.close('all')

    ##plt.semilogx(np.array(frontfits)[:,0], np.array(frontfits)[:,1], 'bo', markeredgecolor='b')
    #plt.semilogx(np.array(popfits)[:,0], np.array(popfits)[:,1], 'bo', markeredgecolor='b')
    #for popfit in popfits:
    for ind, popfit in zip(pop, popfits):
        ## journal version
        #plt.semilogx(popfit[0], popfit[1], 'bo',markeredgecolor='b',
                #label=u'flexure: {:d}, shear: {:d}, deck: {:d}'.format(ind[0], ind[1], ind[2]))
        # conference version
        plt.semilogx(popfit[0], popfit[1], 'bo',markeredgecolor='b',
                label=u'({:d},{:d},{:d})'.format(ind[0], ind[1], ind[2]))

    plt.ylim((-1,np.max(popfits)*1.1))
    ax = plt.gca()
    ax.ticklabel_format(axis='y', style='sci', scilimits=(-3,3))

    plt.xlabel(u'Failure probability')
    plt.ylabel(u'Strengthening cost (mm\\textsuperscript{3})')

    ## journal version
    #annotate_text = u'P={x:.2e}, C={y:.2e}\n {{ {label} }}'
    #datacursor(formatter=annotate_text.format,display='multiple', draggable=True,
            #bbox=None, fontsize=9,
            #arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k'))
    # conference version
    annotate_text = u'{label}'
    datacursor(formatter=annotate_text.format,display='multiple', draggable=True,
            bbox=None, fontsize=9,
            arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k'))

    pause = raw_input('press any key after annotation...')

    plt.semilogx(np.array(allfits)[:,0], np.array(allfits)[:,1], 'o', markerfacecolor='lightgrey',
            markeredgecolor='lightgrey', alpha=0.8)
    plt.semilogx(np.array(popfits)[:,0], np.array(popfits)[:,1], 'bo', markeredgecolor='b')
コード例 #8
0
ファイル: x64plots.py プロジェクト: gopastro/pyphamas
    def implot_data(self, bf, data_type='amp',
                    vmin=None, vmax=None,
                    hold=False, title=None,
                    colorbar=True, sti=False, **kwargs):
        self.bf = bf
        if self.bf is None:
            raise Exception("Need to pass in a BinFile instance to plot object")
        self.check_alive() 
        if not hold:
            self.clear()
        if not hasattr(self.bf, 'cross_corr') and not hasattr(self.bf, 'sti_cc'):
            raise Exception("BinFile does not have cross correlation data. get_cross_corr_data() first on binfile")
        if sti:
            if not hasattr(self.bf, 'sti_cc'):
                raise Exception("BinFile does not have sti cross corr data. Run sti_cross_correlate first")
            self.bf.cc = self.bf.sti_cc.mean(axis=3).mean(axis=2)
        else:
            self.bf.cc = self.bf.cross_corr.mean(axis=2)
        if MATPLOTLIBV1_0:
            interpolation = 'none'
        else:
            interpolation = 'nearest'
        if data_type == 'amp':
            self.image = self.imshow(10*numpy.log10(numpy.abs(self.bf.cc)),
                                     cmap=cm.spectral, interpolation=interpolation,
                                     vmin=vmin, vmax=vmax,
                                     **kwargs)
        else:
            self.image = self.imshow(numpy.angle(self.bf.cc),
                                     cmap=cm.spectral, interpolation=interpolation,
                                     vmin=vmin, vmax=vmax,
                                     **kwargs)            
        ax, kw = self.plotobj._get_current_axes()
        if MATPLOTLIBV1_0:
            datacursor(self.image, display='single',bbox=dict(fc='white'),
                       arrowprops=dict(arrowstyle='simple', fc='white', alpha=0.5),
                       formatter="x: {x:.0f}\ny: {y:.0f}\nz: {z:.2f}".format)
        def format_coord(x, y):
            if data_type == 'amp':
                z = (10*numpy.log10(numpy.abs(self.bf.cc)))[x, y]
            else:
                z = (numpy.angle(self.bf.cc))[x, y]
            return 'x=%.1f, y=%.1f, z=%.2f' % (x, y, z)


        ax, kw = self.plotobj._get_current_axes()
        ax.format_coord = format_coord
        # self.set_subplot_title(title)
        if title is None:
            title = "%s" % self.bf.basename        
        self.set_subplot_title(title)
        if colorbar:
            self.colorbar()
コード例 #9
0
def Graph_GFS_write():
    print ('inside Graph_GFS graph')
    Plot3 = np.loadtxt('Merge_write.txt')
    Plot4 = np.loadtxt('Merge_read.txt')
    fig = plt.figure()
    pl.subplot(311)
    
    pl.title('Write :: Chunk_and_Block Size vs Speed')    
    pl.xlabel('Chunk_and_Block Size in MB')
    pl.ylabel('Speed in MBps')
    #pl.xlim(0,10)
    
    x = Plot3[:,1]
    y = Plot3[:,3]
    yerr = Plot3[:,4]
    xticks = Plot3[:,1]
    #plt.xticks(xticks)
    plt.xscale('log')
    #plt.yscale('log')
    #plt.xticks(xticks)
    pl.errorbar(x,y,yerr,ecolor='b')
    #pl.plot(x,y, 'b-', marker ='o',)
    datacursor(display='multiple', draggable=True)
    #cursor = Dcursor.FollowDotCursor(ax, x, y)
    #plt.show()
    #pl.show()

    
    pl.subplot(313)    
    pl.title('Read :: Chunk_and_Block Size vs Speed')    
    pl.xlabel('Chunk_and_Block Size in MB')
    pl.ylabel('Speed in MBps')
    #pl.xlim(0,10)
    
    x = Plot4[:,1]
    y = Plot4[:,3]
    yerr = Plot4[:,4]
    xticks = Plot4[:,1]
    pl.xticks(xticks)
    plt.xscale('log')
    pl.errorbar(x,y,yerr,ecolor='b')
    datacursor(display='multiple', draggable=True)
    #pl.plot(x,y, 'b-', marker = 'o')
    #pl.show()
    #Dcursor2.DataCursor([write,read])
    pl.show()
    pl.savefig('GFS_Reading.ps')
    pl.savefig('GFS_Reading.png')
    pl.savefig('GFS_Reading.pdf')
    print ('endddd')
    
    plt.close(fig)
コード例 #10
0
ファイル: plot.py プロジェクト: SaulAryehKohn/capo
def omni_view(reds,vis,pol,int=10,chan=500,norm=False,cursor=True,save=None,colors=None,symbols=None, ex_ants=[]):
    if not colors:
        colors = ["#006BA4", "#FF7F0E", "#2CA02C", "#D61D28", "#9467BD", "#8C564B", "#E377C2", "#7F7F7F", "#BCBD22", "#17BECF"]
    if not symbols: 
        symbols = ["o", "v", "^", "<", ">", "*"]
    points = []
    sym = []
    col = []
    bl = []
    ngps = len(reds)
    if save:
        plt.clf()
        plt.cla()
    for i,gp in enumerate(reds):
        c = colors[i%len(colors)]
        s = symbols[i/len(colors)]
        for r in gp:
            if np.any([ant in r for ant in ex_ants]): continue
            try:
                points.append(vis[r][pol][int,chan])
                bl.append(r)
            except(KeyError):
                points.append(np.conj(vis[r[::-1]][pol][int,chan]))
                bl.append(r[::-1])
            sym.append(s)
            col.append(c)
    points = np.array(points)
    max_x=0
    max_y=0
    ax = plt.subplots(111)
    for i,pt in enumerate(points):
        if norm:
            ax.scatter(pt.real/np.abs(pt), pt.imag/np.abs(pt), c=col[i], marker=sym[i], s=50, label='{}'.format(bl[i]))
        else:        
            ax.scatter(pt.real, pt.imag, c=col[i], marker=sym[i], s=50, label='{}'.format(bl[i]))
            if np.abs(pt.real) > max_x: max_x = np.abs(pt.real)
            if np.abs(pt.imag) > max_y: max_y = np.abs(pt.imag)
            
    if norm:         
        plt.xlim(-1,1)
        plt.ylim(-1,1)
    else: 
        plt.xlim(-max_x-.1*max_x,max_x+.1*max_x)
        plt.ylim(-max_y-.1*max_y,max_y+.1*max_y)
    plt.ylabel('imag(V)')
    plt.xlabel('real(V)')
    if cursor:
        from mpldatacursor import datacursor
        datacursor(formatter='{label}'.format)
    if save:
        plt.savefig(save)
    return None
def lifetimefitting(icorr_mean_list, str_yr_list=[0., 0., 0.]):
    from scipy import stats
    from scipy.optimize import curve_fit

    # load data
    suffix = rate2suffix(icorr_mean_list)
    filename = 'pfhistory_str_'
    for ti in str_yr_list:
        filename = filename + str(int(ti)) + '_'
    datapath = os.path.join(os.path.abspath('./'), 'data')
    filename = filename+suffix+'.npz'
    datafile = os.path.join(datapath,filename)

    if os.path.isfile(datafile) is False:
        print 'no data available, execute Life_Cycle_History.py with \
                icorr_mean_list={} and str_yr_list={} fist'.format(icorr_mean_list,
                        str_yr_list)
        sys.exit(1)
    else:
        pfhistory = np.load(datafile)
        time_array = pfhistory['time']
        pf_sys = pfhistory['system']
        # lifetime fitting
        # candidate cdfs
        def fitexpon(xdata, *params):
            lbd = params[0]
            return stats.expon.cdf(xdata, scale=1./lbd)
        def fitweibull(xdata, *params):
            k = params[0]    # shape param k in Weibull wiki
            lbd = params[1]    # scale param lbd in Weibull wiki
            return stats.weibull_min.cdf(xdata, k, scale=lbd)
        def fitgamma(xdata, *params):
            k=params[0]
            theta = params[1]
            return stats.gamma.cdf(xdata, k, scale=theta)
        poptExpon, pcovExpon = curve_fit(fitexpon, time_array, pf_sys, p0=[1.], bounds=(0.,np.inf))
        poptWbl, pcovWbl = curve_fit(fitweibull, time_array, pf_sys, p0=[1.,5.], bounds=([0.,0.],[np.inf, np.inf]))
        poptGamma, pcovGamma = curve_fit(fitgamma, time_array, pf_sys, p0=[1.,1.], bounds=([0.,0.],[np.inf,np.inf]))

    plt.ion()
    plt.figure()
    plt.semilogy(time_array, pf_sys, 'o', label='$T_f$ data')
    plt.semilogy(time_array, fitexpon(time_array, poptExpon[0]), ls='--', label='Exponential')
    plt.semilogy(time_array, fitweibull(time_array,poptWbl[0],poptWbl[1]), ls='-', label='Weibull')
    plt.semilogy(time_array, fitgamma(time_array,poptGamma[0],poptGamma[1]), ls=':', label='Gamma')
    plt.xlabel('Time (year)')
    plt.ylabel('Failure probability')
    #plt.legend(loc='lower right', fontsize=9)

    datacursor(formatter='{label}'.format,display='multiple', draggable=True,
            bbox=None, fontsize=9,
            arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k'))
コード例 #12
0
def plot_avg_time_locked_data(timeLockedData, timeAxis, subplot=None, timeToPlot=None, remove_channels=None, picker=None, labels=False, figure_id=0, figure=None):
    if timeToPlot==None:
        if np.size(np.shape(timeLockedData)) > 1:
            samplesToPlot = [0, np.shape(timeLockedData)[1]]
        else:
            samplesToPlot = [0, np.shape(timeLockedData)[0]]
    else:
        Freq = len(timeAxis)/(timeAxis[-1]-timeAxis[0])
        startingTimeDif = timeToPlot[0] - timeAxis[0]
        endingTimeDif = timeToPlot[1] - timeAxis[0]
        if startingTimeDif < 0:
            raise ArithmeticError("The starting time to plot must be after the starting time of the trial")
        if endingTimeDif < 0:
            raise ArithmeticError("The end time to plot must be after the starting time of the trial")
        samplesToPlot = [startingTimeDif*Freq, endingTimeDif*Freq]

    if figure is None:
        fig = plt.figure(figure_id)
    else:
        fig = figure

    if subplot is not None:
        ax = fig.add_subplot(subplot)
    else:
        ax = fig.add_subplot(111)

    if picker:
        def on_pick(event):
            event.artist.set_visible(not event.artist.get_visible())
            print(ax.lines.index(event.artist))
            fig.canvas.draw()
        fig.canvas.callbacks.connect('pick_event', on_pick)


    if remove_channels is not None:
        timeLockedData[remove_channels, :] = float('nan')
    if np.size(np.shape(timeLockedData)) > 1:
        lines = ax.plot(timeAxis[samplesToPlot[0]:samplesToPlot[1]], np.transpose(timeLockedData[:, samplesToPlot[0]:samplesToPlot[1]]), picker=picker)
    else:
        lines = ax.plot(timeAxis[samplesToPlot[0]:samplesToPlot[1]], timeLockedData[samplesToPlot[0]:samplesToPlot[1]], picker=picker)

    if labels:
        datacursor(hover=True)
        for i in np.arange(0,len(lines)):
            lines[i].set_label(str(i))

    fig.add_subplot(ax)

    plt.show()
    return ax
コード例 #13
0
def plot_iv(data,range,res,symbol):
    fig=plt.figure()
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twiny()
    act,=ax1.plot(data.DELTA,data.VOLATILITY,'r*',label='Actual Smile')
    fit,=ax1.plot(range,res,'g',label='Fitted Smile')
    ax1.set_xlabel('DELTA')
    ax1.set_ylabel('VOLATILITY')
    #ax2.plot(data.STRIKE_PR,data.VOLATILITY,'b*',label='Actual Smile')
    ax2.set_xticks(data.DELTA)
    ax2.set_xticklabels(data.STRIKE_PR,rotation=90,fontsize=12)
    
    ax2.set_xlabel('STRIKE')
    #plt.show()
    datacursor()
    plt.savefig("%s_VOL.jpg"%symbol)
コード例 #14
0
ファイル: main.py プロジェクト: erwanp/qtplaskin
    def datacursor(self, widget, unit=None, labname='Label'):
        ''' Plot datacursors (useful when the number of lines gets confusing)

        Parameters
        ----------

        unit and labname: 
            to customize the info box'''

        # Clean previous cursors  (prevent overlaps with remaining cursors)
        while len(self.cursors) > 0:
            dc = self.cursors.pop()
            dc.hide().disable()

        if self.actionDatacursor.isChecked() and CURSOR_AVAIL:

            def formatter(x=None, y=None, z=None, s=None, label=None, **kwargs):

                ax = kwargs['event'].mouseevent.inaxes

                output = []
                output.append(u't: {0:0.3e} s'.format(x))
                output.append(u'y: {0:0.3e} {1}'.format(y, unit))

                for key, val in zip(['z', 's'], [z, s]):
                    if val is not None:
                        try:
                            output.append(
                                u'{key}: {val:0.3e}'.format(key=key, val=val))
                        except ValueError:
                            # X & Y will be strings at this point.
                            # For masked arrays, etc, "z" and s values may be a
                            # string
                            output.append(
                                u'{key}: {val}'.format(key=key, val=val))

                # label may be None or an empty string (for an un-labeled AxesImage)...
                # Un-labeled Line2D's will have labels that start with an
                # underscore
                if label and not label.startswith('_'):
                    output.append(u'{0}: {1}'.format(labname, label))

                if kwargs.get(u'point_label', None) is not None:
                    output.append(
                        u'Point: ' + u', '.join(kwargs['point_label']))

                return u'\n'.join(output)

            for ax in widget.axes:
                if not ax.cursorlines is None:
                    self.cursors.append(mpldatacursor.datacursor(
                        ax.cursorlines, hover=True, size=10, color='k',
                        bbox=dict(fc='white', alpha=0.9),
                        formatter=formatter))
        return None
def front_deprecated(icorr_mean_list):
    suffix = rate2suffix(icorr_mean_list)
    # load data
    datapath = os.path.join(os.path.abspath('./'), 'data')
    filename = 'popdata_'+suffix+'.npz'
    datafile = os.path.join(datapath,filename)
    if os.path.isfile(datafile) is False:
        print 'no data available, execute Life_Cycle_Optimization.py with \
                icorr_mean_list={} fist'.format(icorr_mean_list)
        sys.exit(1)
    else:
        popdata = np.load(datafile)
        # all pop is the same as pop
        allpop = popdata['allpop']
        allfits = popdata['allfits']
        front = popdata['front']
        frontfits = popdata['frontfits']
        pop = popdata['pop']
        popfits = popdata['popfits']

    plt.ion()
    plt.figure()

    ##plt.semilogx(np.array(frontfits)[:,0], np.array(frontfits)[:,1], 'bo', markeredgecolor='b')
    for ind, popfit in zip(front, frontfits):
        plt.semilogx(popfit[0], popfit[1], 'bo',
                label=u'flexure: {:d}, shear: {:d}, deck: {:d}'.format(ind[0], ind[1], ind[2]))

    plt.ylim((-1,np.max(popfits)*1.01))
    ax = plt.gca()
    ax.ticklabel_format(axis='y', style='sci', scilimits=(-3,3))

    plt.xlabel(u'Failure probability (log scale)', fontsize=12)
    plt.ylabel(u'Strengthening cost (mm\\textsuperscript{3})', fontsize=12)

    annotate_text = u'P={x:.2e}, C={y:.2e}\n {{ {label} }}'
    datacursor(formatter=annotate_text.format,display='multiple', draggable=True,
            bbox=None, fontsize=12,
            arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k'))

    pause = raw_input('press any key after annotation...')
コード例 #16
0
ファイル: models.py プロジェクト: Minios0903/Ferro
    def u_plot(self, pvals, ufe):
        """
        Plots U vs P for landau film.
        
        Parameters
        ----------
        pvals: 1d np array of polarization charge values
        ufe: 1d np array of energy densities calculated at xVals.
            
        Returns
        -------
        n/a
        """

        fig1 = plt.figure()
        fig1.set_facecolor("white")
        plt.cla()
        ax1 = fig1.add_subplot(111)
        datacursor(ax1.plot(pvals * 1e6, ufe))
        ax1.set_xlabel("Polarization Charge, P (uC/cm^2)")
        ax1.set_ylabel("Energy, U")
コード例 #17
0
ファイル: datacursor_easy.py プロジェクト: iancraz/TC-TP05
def make_datacursor(mode, filename, my_plt, fig):
    if mode == "mag":
        datacursor(display='multiple',
                   tolerance=10,
                   formatter="Freq: {x:.3e}  Hz \nAmp:{y:.1f} Db".format,
                   draggable=True)
    else:
        datacursor(display='multiple',
                   tolerance=10,
                   formatter="Freq: {x:.3e}  Hz \nFase:{y:.1f} grados".format,
                   draggable=True)
    my_plt.minorticks_on()
    my_plt.grid(which='major', linestyle='-', linewidth=0.3, color='black')
    my_plt.grid(which='minor', linestyle=':', linewidth=0.1, color='black')

    my_plt.show()
    input("Press Enter ")

    fig.savefig(filename, dpi=300)
    my_plt.cla()
    my_plt.close()
コード例 #18
0
ファイル: datacursor_easy.py プロジェクト: iancraz/TC-TP05
def make_datacursor_zin(mode, filename, my_plt, fig, ax):
    add_legend_zin(mode, ax, my_plt)

    if mode == "mag":
        datacursor(
            display='multiple',
            tolerance=10,
            formatter="Freq: {x:.3e}  Hz \nZin:{y:.1f} K $\Omega$".format,
            draggable=True)
    else:
        datacursor(display='multiple',
                   tolerance=10,
                   formatter="Freq: {x:.3e}  Hz \nFase:{y:.1f} grados".format,
                   draggable=True)

    my_plt.show()
    input("Press Enter ")

    fig.savefig(filename, dpi=300)
    my_plt.cla()
    my_plt.close()
コード例 #19
0
ファイル: nist_asd_parser.py プロジェクト: erwanp/nist-asd
    def plot_nist_lines_to_axis(self, axis, normalize_max=None, legend=True, measure='Aki', alpha=0.5):  # measure='Aki'
        if self._check_download_conditions():
            self.get_lines()

        logger.info("Plotting NIST lines to {0}".format(axis))
        specs = np.array(list(set([l['spectrum'] for l in self.lines])))
        specs.sort()

        maxi = self._get_maximum_relative_intensity(measure)

        lines = []
        lines_spec = list(np.zeros(len(specs)))

        for i in range(0,len(self.lines)):
            wl = self.lines[i]['wave']
            if wl > self.lower_wavelength and wl < self.upper_wavelength:
                ispc, = np.nonzero(np.ravel(specs == self.lines[i]['spectrum']))
                
                self.colr = plt.cm.get_cmap('tab20c_r')(float(ispc)/len(specs))

                if normalize_max is None:
                    ri = float(self.lines[i][measure])
                else:
                    ri = float(self.lines[i][measure]) / maxi * normalize_max

                lines.append(axis.plot([wl, wl], [0., ri if not isnan(ri) else 1.e-6], '.-', lw=1., color=self.colr, alpha=alpha)[0])

                assert len(ispc) == 1  # dont know if correct, but working
                lines_spec[ispc[0]] = lines[-1]
        # datacursor(lines)
        logger.info("Plotting {0} lines of {1} in total for {2} from "
                    "{3:2.3e} to {4:2.3e} nm".format(len(lines), len(self.lines), self.spectrum, self.lower_wavelength,
                                                     self.upper_wavelength))
        
        datacursor(lines, formatter='{x} nm'.format)

        if legend:
            if len(specs) > 1:
                # axis.legend(handles=lines_spec, labels=specs, loc=0)
                axis.legend(lines_spec, specs, loc=0)
コード例 #20
0
ファイル: FFT.py プロジェクト: nathalyeda/Python
    def PlotFFT(self):

        fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(80, 60))

        # signal plot
        axs[0].plot(self.t, self.f)
        axs[0].grid()
        axs[0].set_xlabel('time (s)', fontsize=16)
        axs[0].set_ylabel('Voltage', fontsize=16)
        axs[0].set_title('Signal', fontweight='bold', fontsize=20)

        # frequency
        freqs, Ampts = self.Freq()

        h = axs[1].plot(freqs, Ampts, 'r')
        datacursor(h)
        axs[1].grid()
        axs[1].set_xlabel('frequency (Hz)', fontsize=16)
        axs[1].set_ylabel('Voltage', fontsize=16)
        axs[1].set_title('FFT', fontweight='bold', fontsize=20)

        plt.show()
コード例 #21
0
    def drawChunkChangePlot(self):
        x = range(0, len(self.changedChunksAll))
        fig, ax = plt.subplots()

        ax.plot(x, self.changedChunksBlock, label='changedChunksBlock')
        ax.plot(x, self.changedChunksBlockEntity, label='changedChunksBlockEntity')
        ax.plot(x, self.changedChunksEntity, label='changedChunksEntity')
        ax.plot(x, self.changedChunksAll, label='changedChunksAll')

        # ax.plot(self.serverWorldTimeTicks, self.changedEntities, label='# changed entities', linestyle="-", color='g')

        # ax.plot(self.serverWorldTimeTicks, self.changedTileEntities, label='# changed tile entities', color='orange')
        # ax.plot(self.serverWorldTimeTicks, self.changedBlocks, label='# changed blocks', color='red')
        # ax.plot(self.serverWorldTimeTicks, self.changedSections, label='# changed sections', linestyle='-',
        #        color='blue')
        # ax.plot(self.serverWorldTimeTicks, self.changedChunks, label='# changed chunks', color='black')

        plt.legend()
        ax.set(xlabel='Interval number (' + self.intervalLength + "s per Interval)", ylabel='Changed Chunks', title='Changed Chunks over time')
        ax.grid()
        datacursor()
        plt.show()
def costkeeping(icorr_mean_list):
    suffix = rate2suffix(icorr_mean_list)
    # load data
    datapath = os.path.join(os.path.abspath('./'), 'data')
    filename = 'costkeeping_'+suffix+'.npz'
    datafile = os.path.join(datapath,filename)
    if os.path.isfile(datafile) is False:
        print 'no data available, execute Life_Cycle_Optimization.py with \
                icorr_mean_list={} fist'.format(icorr_mean_list)
        sys.exit(1)
    else:
        costkeeping = np.load(datafile)

    plt.ion()
    plt.figure()
    plt.plot(costkeeping['flexure'][0,:], costkeeping['flexure'][1,:], 'b-',
            label='Flexure (girder)')
    plt.plot(costkeeping['shear'][0,:], costkeeping['shear'][1,:], 'r--',
            label='Shear (girder)')
    plt.plot(costkeeping['deck'][0,:], costkeeping['deck'][1,:], 'g-.',
            label='Deck')
    service_life = np.max((np.max(costkeeping['flexure'][0,:]),
            np.max(costkeeping['shear'][0,:]), np.max(costkeeping['deck'][0,:])))
    max_cost = np.max((np.max(costkeeping['flexure'][1,:]),
            np.max(costkeeping['shear'][1,:]), np.max(costkeeping['deck'][1,:])))
    plt.xlim((-1,service_life+1))
    plt.ylim((-1,max_cost*1.01))

    plt.xlabel('Strengthening time (year)')
    plt.ylabel('Volumn of FRP (mm\\textsuperscript{3})')

    ax = plt.gca()
    ax.ticklabel_format(axis='y', style='sci', scilimits=(-3,3))

    datacursor(formatter='{label}'.format,display='multiple', draggable=True,
            bbox=None, fontsize=9,
            arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k'))

    pause = raw_input('press any key after annotation...')
コード例 #23
0
ファイル: subs.py プロジェクト: flipperbw/youtube-stats
def show_plot():
    plt.ioff()

    plt.rcParams['figure.figsize'] = [20, 15]

    _fig, ax = plt.subplots()

    x = [d[0] for d in n]
    y = [d[1] for d in n]

    ax.scatter(x, y, s=5)

    mpldatacursor.datacursor(date_format="%x", bbox={
        'boxstyle': 'round,pad=0.5',
        'fc': 'lightblue',
        'alpha': 0.95,
        'edgecolor': 'black'
    })

    plt.ion()

    plt.show()
コード例 #24
0
    def noMoreIntervals(self):
        fig, ax = plt.subplots()
        ax.plot(self.timepoints,
                self.loaded_chunks,
                label='#loaded chunks',
                linestyle="-",
                color='g')

        ax.plot(self.timepoints,
                self.tile_entities,
                label='#tile entities',
                color='orange')
        ax.plot(self.timepoints, self.entities, label='#entities', color='red')
        #ax.plot(self.timepoints, self.changed_entities, label='#changed entities', linestyle='--', color='red')

        ax.plot(self.timepoints,
                self.diff_times,
                label='#time for statediff [ms]',
                color='black')

        ax2 = ax.twinx()
        ax2.plot(self.timepoints,
                 self.online_players,
                 label='#online players',
                 color='b')
        #ax2.plot(self.timepoints, self.changed_chunks, label='#changed chunks', linestyle='--', color='g')
        #ax2.plot(self.timepoints, self.changed_tile_entities, label='#changed tile entities', linestyle='--', color='orange')

        # fix legend
        # lines, labels = ax.get_legend_handles_labels()
        # lines2, labels2 = ax2.get_legend_handles_labels()
        # ax.legend(lines + lines2, labels + labels2, loc=2)
        ax.legend(loc=2)  # upper left
        ax2.legend(loc=1)  # upper right

        ax.set(xlabel='Time', title='Status information')
        ax.grid()
        datacursor()
        plt.show()
コード例 #25
0
ファイル: tsCluster.py プロジェクト: iabraham/tscluster
        def plot(sample, matrix):
            """ Helper function that does the actual plotting.

                Arguments:
                    sample: An element of self.samples
                    matrix: A string specifying which matrix to visualize. Must be 'ULM', 'SLM' of 'CM'
            """
            mat_name = {
                'CM': 'Correlation Matrix - ',
                'ULM': 'Lead Matrix - ',
                'SLM': 'Sorted Lead Matrix - '
            }
            mpl.figure()
            try:
                mpl.imshow(sample[matrix], interpolation=None)
            except KeyError:
                print('Error! Matrix not found. "mat" must be ULM, CM or SLM')
            mpl.title(mat_name[matrix] + sample['Name'] + ':' +
                      sample['Session'] + '-' + sample['Run'] + '(' +
                      sample['Location'] + ')')
            mpl.colorbar()
            mpldatacursor.datacursor(bbox=dict(alpha=1, fc='w'),
                                     formatter=label_point)
コード例 #26
0
 def plot_rl(self):
   if self.cursor is not None: self.cursor.hide().disable()
   matplotlib.rcdefaults()
   self.figure.clf()
   self.figure.subplots_adjust(left = 0.12, bottom = 0.12, right = 0.88, top = 0.98)
   axes1 = self.figure.add_subplot(111)
   axes1.cla()
   axes1.xaxis.set_major_formatter(FuncFormatter(metric_prefix))
   axes1.set_xlabel('Hz')
   axes1.set_ylabel('Return loss, dB')
   magnitude = np.absolute(self.gamma())
   axes1.plot(self.xaxis, 20.0 * np.log10(magnitude), color = 'blue', label = 'Return loss')
   self.cursor = datacursor(axes = self.figure.get_axes(), formatter = LabelFormatter(), display = 'multiple')
   self.canvas.draw()
コード例 #27
0
def get_opt_vol_data_hist(symbol):
    
    db=MySQLdb.connect(config.host,config.user,config.password,'NSE')
    
    points=pd.DataFrame()
    fig=plt.figure()
    for i in [0,1,5]:
        
        date=pd.read_sql(last_date_query%i,db)
        date=date.timestamp[0].__str__()
        data=get_opt_vol_data(symbol, date)
        (range,res,pol)=perform_spline_calc(data, xlow=0, xhigh=1, xsep=0.02)
        
        if i==0:
            points=data.DELTA
            ax1 = fig.add_subplot(111)
            ax2 = ax1.twiny()
            act,=ax1.plot(data.DELTA,data.VOLATILITY,'r*',label='Actual Smile')
            fit,=ax1.plot(range,res,'g',label='Fitted Smile')
            ax1.set_xlabel('DELTA')
            ax1.set_ylabel('VOLATILITY')
            
            #ax2.plot(data.STRIKE_PR,data.VOLATILITY,'b*',label='Actual Smile')
            ax2.set_xticks(data.DELTA)
            ax2.set_xticklabels(data.STRIKE_PR,rotation=90,fontsize=12)
            ax2.set_xlabel('STRIKE')
        elif i==1:
            ax1.plot(points,pol(points),'r',label='1 day ago')
        else:
            ax1.plot(points,pol(points),'b',label='7 days ago')
        lgd=ax1.legend(loc='upper left',bbox_to_anchor=(1,1))
        datacursor()
        fig.savefig("%s_VOL.jpg"%symbol, bbox_extra_artists=(lgd,), bbox_inches='tight')
            
                
        
    db.close()
コード例 #28
0
    def plot(self, dataframe, param, param2, color='red', label='no', ax=None):
        df = self.select(dataframe, param)
        df2 = self.select(dataframe, param2)
        comb_df = df.join(df2)

        if label == 'no':
            comb_df.plot.scatter(x=param,
                                 y=param2,
                                 color=color,
                                 title=param + ' Vs ' + param2)
            datacursor(hover=True, point_labels=comb_df.index)

            # getting the summary
            print df.describe()
            print df2.describe()
            print comb_df
            plt.show()
            #return dataframe.plot()
        else:
            if ax == None:
                return comb_df.plot.scatter(x=param,
                                            y=param2,
                                            color=color,
                                            label=label)
            else:
                comb_df.plot.scatter(x=param,
                                     y=param2,
                                     color=color,
                                     label=label,
                                     ax=ax,
                                     title=param + ' Vs ' + param2)
                datacursor(hover=True, point_labels=comb_df.index)
                # getting the summary
                print df.describe()
                print df2.describe()
                print comb_df
                plt.show()
コード例 #29
0
    def set_data_cursor(self):
        if self.current_plot_idx is None:
            return None

        # Use a DataCursor to interactively display the label
        # for artists of the current axes.
        self.data_cursor = mpldatacursor.datacursor(
            axes=self.plots[self.current_plot_idx],
            formatter='{label}'.format,
            tolerance=4,
            # hover=True,
            # display='single',
            display='multiple',
            draggable=True,
        )
コード例 #30
0
ファイル: datacursor_easy.py プロジェクト: iancraz/TC-TP05
def make_datacursor_general(x1, u1, filename, my_plt, ax1):
    datacursor(display='multiple',
               tolerance=0,
               formatter=(str(x1) + " (" + str(u1) +
                          "): {x:.3e}  Hz \n").format,
               draggable=True)

    my_plt.gca().minorticks_on()
    my_plt.gca().grid(which='major',
                      linestyle='-',
                      linewidth=0.3,
                      color='black')
    my_plt.gca().grid(which='minor',
                      linestyle=':',
                      linewidth=0.1,
                      color='black')

    # my_plt.show()
    # input("Press Enter ")

    my_plt.gcf().savefig(filename, dpi=300)

    my_plt.cla()
    my_plt.close()
コード例 #31
0
ファイル: network_plot.py プロジェクト: chan-y-park/mose
    def set_data_cursor(self):
        if self.current_plot_idx is None:
            return None

        # Use a DataCursor to interactively display the label
        # for artists of the current axes.
        self.data_cursor = mpldatacursor.datacursor(
            axes=self.plots[self.current_plot_idx],
            formatter='{label}'.format,
            tolerance=4,
            hover=True,
            #display='single',
            #display='multiple',
            #draggable=True,
        )
コード例 #32
0
 def plot_swr(self):
   if self.cursor is not None: self.cursor.hide().disable()
   matplotlib.rcdefaults()
   self.figure.clf()
   self.figure.subplots_adjust(left = 0.12, bottom = 0.12, right = 0.88, top = 0.98)
   axes1 = self.figure.add_subplot(111)
   axes1.cla()
   axes1.xaxis.set_major_formatter(FuncFormatter(metric_prefix))
   axes1.yaxis.set_major_formatter(FuncFormatter(metric_prefix))
   axes1.set_xlabel('Hz')
   axes1.set_ylabel('SWR')
   magnitude = np.absolute(self.gamma())
   swr = np.maximum(1.0, np.minimum(100.0, (1.0 + magnitude) / np.maximum(1.0e-20, 1.0 - magnitude)))
   axes1.plot(self.xaxis, swr, color = 'blue', label = 'SWR')
   self.cursor = datacursor(axes = self.figure.get_axes(), formatter = LabelFormatter(), display = 'multiple')
   self.canvas.draw()
コード例 #33
0
 def plot_smith(self):
   if self.cursor is not None: self.cursor.hide().disable()
   matplotlib.rcdefaults()
   self.figure.clf()
   self.figure.subplots_adjust(left = 0.0, bottom = 0.0, right = 1.0, top = 1.0)
   axes1 = self.figure.add_subplot(111)
   self.plot_smith_grid(axes1, 'blue')
   gamma = self.gamma()
   plot, = axes1.plot(gamma.real, gamma.imag, color = 'red')
   axes1.axis('equal')
   axes1.set_xlim(-1.12, 1.12)
   axes1.set_ylim(-1.12, 1.12)
   axes1.xaxis.set_visible(False)
   axes1.yaxis.set_visible(False)
   for loc, spine in axes1.spines.items():
     spine.set_visible(False)
   self.cursor = datacursor(plot, formatter = SmithFormatter(self.xaxis), display = 'multiple')
   self.canvas.draw()
コード例 #34
0
ファイル: mainGUI.py プロジェクト: cjsantucci/fantasyTool
    def createFigure(self):
        #         tkf= tk.Frame()
        #         self.mainFig= matplotlib.figure.Figure(figsize= (5,5),dpi=100)
        self.mainFig = plt.figure()
        a = self.mainFig.add_subplot(111)
        line = a.plot([1, 2, 3, 4, 5, 6, 7, 8], [5, 6, 1, 3, 8, 9, 3, 5])

        #         plt.show( block= False )

        root = tk.Tk()
        root.iconbitmap('/home/chris/Desktop/download.jpg')
        root.title("blah")
        canvas = FigureCanvasTkAgg(self.mainFig, master=root)
        canvas.show()
        canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

        toolbar = NavigationToolbar2TkAgg(canvas, root)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        dcObj = datacursor(line, snap=True)
        print()
コード例 #35
0
 def plot_magphase(self, data):
   if self.cursor is not None: self.cursor.hide().disable()
   matplotlib.rcdefaults()
   self.figure.clf()
   self.figure.subplots_adjust(left = 0.12, bottom = 0.12, right = 0.88, top = 0.98)
   axes1 = self.figure.add_subplot(111)
   axes1.cla()
   axes1.xaxis.set_major_formatter(FuncFormatter(metric_prefix))
   axes1.yaxis.set_major_formatter(FuncFormatter(metric_prefix))
   axes1.tick_params('y', color = 'blue', labelcolor = 'blue')
   axes1.yaxis.label.set_color('blue')
   axes1.plot(self.xaxis, np.absolute(data), color = 'blue', label = 'Magnitude')
   axes2 = axes1.twinx()
   axes2.spines['left'].set_color('blue')
   axes2.spines['right'].set_color('red')
   axes1.set_xlabel('Hz')
   axes1.set_ylabel('Magnitude')
   axes2.set_ylabel('Phase angle')
   axes2.tick_params('y', color = 'red', labelcolor = 'red')
   axes2.yaxis.label.set_color('red')
   axes2.plot(self.xaxis, np.angle(data, deg = True), color = 'red', label = 'Phase angle')
   self.cursor = datacursor(axes = self.figure.get_axes(), formatter = LabelFormatter(), display = 'multiple')
   self.canvas.draw()
コード例 #36
0
def plot_cluster_lines(estimator,
                       X,
                       fig=None,
                       ax=None,
                       sample_colors=None,
                       sample_labels=None,
                       cluster_labels=None,
                       colormap=plt.cm.get_cmap('rainbow'),
                       xlabel=None,
                       ylabel=None,
                       title=None):
    """Implementation of the plotting of the results of the
    :func:`Fuzzy K-Means <fda.clustering.fuzzy_kmeans>` method.


    A kind of Parallel Coordinates plot is generated in this function with the
    membership values obtained from the algorithm. A line is plotted for each
    sample with the values for each cluster. See `Clustering Example
    <../auto_examples/plot_clustering.html>`_.

    Args:
        estimator (BaseEstimator object): estimator used to calculate the
            clusters.
        X (FDataGrd object): contains the samples which are grouped
            into different clusters.
        fig (figure object, optional): figure over which the graph is
            plotted in case ax is not specified. If None and ax is also None,
            the figure is initialized.
        ax (axis object, optional): axis over where the graph is  plotted.
            If None, see param fig.
        sample_colors (list of colors, optional): contains in order the colors of each
            sample of the fdatagrid.
        sample_labels (list of str, optional): contains in order the labels
            of each sample  of the fdatagrid.
        cluster_labels (list of str, optional): contains in order the names of each
            cluster the samples of the fdatagrid are classified into.
        colormap(colormap, optional): colormap from which the colors of the plot are taken.
        xlabel (str): Label for the x-axis. Defaults to "Sample".
        ylabel (str): Label for the y-axis. Defaults to "Membership grade".
        title (str, optional): Title for the figure where the clustering results are ploted.
            Defaults to "Membership grades of the samples to each cluster".

    Returns:
        (tuple): tuple containing:

            fig (figure object): figure object in which the graphs are plotted in case ax is None.

            ax (axes object): axes in which the graphs are plotted.

    """
    fdatagrid = X
    _check_if_estimator(estimator)

    if not isinstance(estimator, FuzzyKMeans):
        raise ValueError("The estimator must be a FuzzyKMeans object.")

    try:
        estimator._check_is_fitted()
        estimator._check_test_data(X)
    except NotFittedError:
        estimator.fit(X)

    fig, ax = _fig_and_ax_checks(fig, ax)

    _plot_clustering_checks(estimator, fdatagrid, sample_colors, sample_labels,
                            None, cluster_labels, None, None)

    xlabel, ylabel, title = _set_labels(xlabel, ylabel, title, "Cluster")

    if sample_colors is None:
        cluster_colors = colormap(
            np.arange(estimator.n_clusters) / (estimator.n_clusters - 1))
        labels_by_cluster = np.argmax(estimator.labels_, axis=1)
        sample_colors = cluster_colors[labels_by_cluster]

    if sample_labels is None:
        sample_labels = [
            '$SAMPLE: {}$'.format(i) for i in range(fdatagrid.nsamples)
        ]

    if cluster_labels is None:
        cluster_labels = [
            '${}$'.format(i) for i in range(estimator.n_clusters)
        ]

    ax.get_xaxis().set_major_locator(MaxNLocator(integer=True))
    for i in range(fdatagrid.nsamples):
        ax.plot(np.arange(estimator.n_clusters),
                estimator.labels_[i],
                label=sample_labels[i],
                color=sample_colors[i])
    ax.set_xticks(np.arange(estimator.n_clusters))
    ax.set_xticklabels(cluster_labels)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    datacursor(formatter='{label}'.format)

    fig.suptitle(title)
    return fig, ax
コード例 #37
0
ファイル: vis.py プロジェクト: Matterhorn-eth/pymh
def plot(fn,
         inprefix='model_full', inpath=os.curdir,
         outprefix='model_ibc', outpath=os.curdir,
         ext='.su', isSU=True, endian='Little',
         clip=1e3, aspect='auto', cmap='seismic',
         interpolation='bicubic', title=None,
         colorbar=True, style='shot_gather',
		 extent=[0, 1, 1, 0],
		 figsize=(10, 8)):

    """ Create a plot """

    if isinstance(fn, basestring):
        data = SEGYFile('/'.join([inpath, fn + ext]), isSU=isSU, endian=endian)
        data = data[:]
    elif isinstance(fn, np.ndarray):
        data = fn
    else:
        raise TypeError('LOL!')

    fig = plt.figure(figsize=figsize, facecolor='w', edgecolor='k')
    gs = gridspec.GridSpec(1, 1)
    ax = fig.add_subplot(gs[0, 0])
    # ax.spines['right'].set_color('none')
    # ax.spines['top'].set_color('none')

    # Remove the ugly ticks
    plt.tick_params(
        which='both',      # both major and minor ticks are affected
        bottom='off',      # ticks along the bottom edge are off
        top='off',        # ticks along the top edge are off
        left='off',        # ticks along the top edge are off
        right='off'        # ticks along the top edge are off
    )

    # Set style-specific attributes
    if style == 'shot_gather':
        clipmin = -clip
        clipmax = +clip
        ax.xaxis.set_label_text('Horizontal location [m]')
        ax.yaxis.set_label_text('Time [s]')
        if title is None:
            ax.set_title('Shot gather')
        else:
            ax.set_title(title)
        cb_label = 'Amplitude'
    elif style == 'slice':
        clipmin = -clip
        clipmax = +clip
        ax.xaxis.set_label_text('Horizontal location [m]')
        ax.yaxis.set_label_text('Depth [m]')
        if title is None:
            ax.set_title('Slice')
        else:
            ax.set_title(title)
        cb_label = 'Amplitude'
    elif style == 'sub_volume_boundary':
        clipmin = -clip
        clipmax = +clip
        ax.xaxis.set_label_text('Horizontal location [m]')
        ax.yaxis.set_label_text('Time [s]')
        if title is None:
            ax.set_title('Volume boundary')
        else:
            ax.set_title(title)
        cb_label = 'Amplitude'
    elif style == 'velocity':
        clipmin = data.min()
        clipmax = data.max()
        #ax.xaxis.set_label_text('Horizontal location [m]')
        ax.xaxis.set_label_text('Inline [m]')
        #ax.yaxis.set_label_text('Crossline [m]')
        ax.yaxis.set_label_text('Depth [m]')
        if title is None:
            ax.set_title('Velocity')
        else:
            ax.set_title(title)
        cb_label = 'Amplitude [m/s]'
    elif style == 'density':
        clipmin = data.min()
        clipmax = data.max()
        ax.xaxis.set_label_text('Horizontal location [m]')
        ax.yaxis.set_label_text('Depth [m]')
        if title is None:
            ax.set_title('Density')
        else:
            ax.set_title(title)
        cb_label = 'Amplitude [kg/m^3]'
    # plt.xticks(np.linspace(2e3,4e3,3))

    # Plot options
    plotopts = {
        'vmin': clipmin,
        'vmax': clipmax,
        'aspect': aspect,
        'cmap': cmap,
        'interpolation': interpolation,
		'extent': extent
    }

    # Create image
    im = ax.imshow(data.T, picker=True, **plotopts)

    # Colorbar
    if colorbar:
        cbax = plt.colorbar(im, orientation='vertical', shrink=0.9)
        cbax.set_ticks(range(int(clipmin+1), int(clipmax+1), int((clipmax-clipmin)/5)))
        cbax.set_label(cb_label)


    datacursor(display='single')

    fig.canvas.mpl_connect('pick_event', onclick)
	#fig.canvas.mpl_connect('button_press_event', onclick)

    plt.show()

    return ax
コード例 #38
0
    def __init__(self, config, global_max_min):
        self.config = config
        print(config)

        _, _, _, self.raw_data, self.glo_max_score, self.glo_min_score = assemble_data(
            config['data'])

        Xs, npz_files, npz_dims, _, _, _ = assemble_data(
            config['data'],
            ext='.' + config['method']['name'] + '.' + config['data']['key'] +
            '.',
            dict_key=config['data']['key'])

        print(self.glo_max_score, self.glo_min_score)
        print(npz_dims, npz_files)
        self.fig = plt.figure(config['data']['key'].upper(), figsize=(14, 7))
        self.ax = self.fig.add_subplot(111)
        plt.subplots_adjust(left=0.5, right=0.9)
        self.fig.canvas.mpl_connect('pick_event', self.onpick)

        checkb_labels = []
        idx = 0
        list_of_artists = []
        labels_cursor = {}
        for data, file in zip(Xs, npz_files):
            print(data.shape)
            algo = file.split('/')[-3]
            rollout = int(file.split('/')[-1].split('_')[0][-1])
            scores = self.raw_data[algo][str(rollout)]['score']
            if global_max_min:
                global_limit = (self.glo_max_score, self.glo_min_score)
            else:
                global_limit = None
            hex_list = color_list(idx % len(COLORS),
                                  scores,
                                  global_limit=global_limit)
            artist = self.ax.scatter(data[:, 0],
                                     data[:, 1],
                                     c=hex_list,
                                     visible=False)

            list_of_artists.append(artist)
            labels_cursor[artist] = []
            for i in range(data.shape[0]):
                labels_cursor[artist].append(algo.upper() + " r" +
                                             str(rollout) + " s" + str(i) +
                                             ": " + str(scores[i]))

            #artist.set_visible(True)
            #artist.set_picker(5)
            artist2data[artist] = (algo, rollout)

            label = algo.upper() + " rollout#" + str(rollout)
            label2artist[label] = artist
            checkb_labels.append(label)
            idx += 1

        formatter = lambda **kwargs: ', '.join(kwargs['point_label'])
        self.dc = datacursor(list_of_artists,
                             hover=True,
                             formatter=formatter,
                             point_labels=labels_cursor)

        checkb_ax = self.fig.add_axes([0.1, 0.1, 0.4, 0.8])
        checkb_ax.axis('off')
        self.checkb = CheckButtons(checkb_ax, checkb_labels,
                                   [False] * len(checkb_labels))
        self.checkb.on_clicked(checkb_click)
コード例 #39
0
ファイル: plot.py プロジェクト: LordHui/sporco
def imview(img,
           title=None,
           copy=True,
           fltscl=False,
           intrp='nearest',
           norm=None,
           cbar=False,
           cmap=None,
           fgsz=None,
           fgnm=None,
           fig=None,
           ax=None):
    """
    Display an image. Pixel values are displayed when the pointer is over
    valid image data.  If a figure object is specified then the image is
    drawn in that figure, and ``fig.show()`` is not called. The figure is
    closed on key entry 'q'.

    Parameters
    ----------
    img : array_like, shape (Nr, Nc) or (Nr, Nc, 3) or (Nr, Nc, 4)
        Image to display
    title : string, optional (default None)
        Figure title
    copy : boolean, optional (default True)
        If True, create a copy of input `img` as a reference for displayed
        pixel values, ensuring that displayed values do not change when the
        array changes in the calling scope. Set this flag to False if the
        overhead of an additional copy of the input image is not acceptable.
    fltscl : boolean, optional (default False)
        If True, rescale and shift floating point arrays to [0,1]
    intrp : string, optional (default 'nearest')
        Specify type of interpolation used to display image (see
        ``interpolation`` parameter of :meth:`matplotlib.axes.Axes.imshow`)
    norm : :class:`matplotlib.colors.Normalize` object, optional (default None)
        Specify the :class:`matplotlib.colors.Normalize` instance used to
        scale pixel values for input to the colour map
    cbar : boolean, optional (default False)
        Flag indicating whether to display colorbar
    cmap : :class:`matplotlib.colors.Colormap`, optional (default None)
        Colour map for image. If none specifed, defaults to cm.Greys_r
        for monochrome image
    fgsz : tuple (width,height), optional (default None)
        Specify figure dimensions in inches
    fgnm : integer, optional (default None)
        Figure number of figure
    fig : :class:`matplotlib.figure.Figure` object, optional (default None)
        Draw in specified figure instead of creating one
    ax : :class:`matplotlib.axes.Axes` object, optional (default None)
        Plot in specified axes instead of current axes of figure

    Returns
    -------
    fig : :class:`matplotlib.figure.Figure` object
      Figure object for this figure
    ax : :class:`matplotlib.axes.Axes` object
      Axes object for this plot
    """

    if img.ndim > 2 and img.shape[2] != 3:
        raise ValueError('Argument img must be an Nr x Nc array or an '
                         'Nr x Nc x 3 array')

    figp = fig
    if fig is None:
        fig = plt.figure(num=fgnm, figsize=fgsz)
        fig.clf()
        ax = fig.gca()
    elif ax is None:
        ax = fig.gca()

    # Deal with removal of 'box-forced' adjustable in Matplotlib 2.2.0
    mplv = matplotlib.__version__.split('.')
    if int(mplv[0]) > 2 or (int(mplv[0]) == 2 and int(mplv[1]) >= 2):
        try:
            ax.set_adjustable('box')
        except Exception:
            ax.set_adjustable('datalim')
    else:
        ax.set_adjustable('box-forced')

    imgd = img.copy()
    if copy:
        # Keep a separate copy of the input image so that the original
        # pixel values can be display rather than the scaled pixel
        # values that are actually plotted.
        img = img.copy()

    if cmap is None and img.ndim == 2:
        cmap = cm.Greys_r

    if np.issubdtype(img.dtype, np.floating):
        if fltscl:
            imgd -= imgd.min()
            imgd /= imgd.max()
        if img.ndim > 2:
            imgd = np.clip(imgd, 0.0, 1.0)
    elif img.dtype == np.uint16:
        imgd = np.float16(imgd) / np.iinfo(np.uint16).max
    elif img.dtype == np.int16:
        imgd = np.float16(imgd) - imgd.min()
        imgd /= imgd.max()

    if norm is None:
        im = ax.imshow(imgd,
                       cmap=cmap,
                       interpolation=intrp,
                       vmin=imgd.min(),
                       vmax=imgd.max())
    else:
        im = ax.imshow(imgd, cmap=cmap, interpolation=intrp, norm=norm)

    ax.set_yticklabels([])
    ax.set_xticklabels([])

    if title is not None:
        ax.set_title(title)

    if cbar or cbar is None:
        orient = 'vertical' if img.shape[0] >= img.shape[1] else 'horizontal'
        pos = 'right' if orient == 'vertical' else 'bottom'
        divider = make_axes_locatable(ax)
        cax = divider.append_axes(pos, size="5%", pad=0.2)
        if cbar is None:
            # See http://chris35wills.github.io/matplotlib_axis
            if hasattr(cax, 'set_facecolor'):
                cax.set_facecolor('none')
            else:
                cax.set_axis_bgcolor('none')
            for axis in ['top', 'bottom', 'left', 'right']:
                cax.spines[axis].set_linewidth(0)
            cax.set_xticks([])
            cax.set_yticks([])
        else:
            plt.colorbar(im, ax=ax, cax=cax, orientation=orient)

    def format_coord(x, y):
        nr, nc = imgd.shape[0:2]
        col = int(x + 0.5)
        row = int(y + 0.5)
        if col >= 0 and col < nc and row >= 0 and row < nr:
            z = img[row, col]
            if imgd.ndim == 2:
                return 'x=%6.2f, y=%6.2f, z=%.2f' % (x, y, z)
            else:
                return 'x=%6.2f, y=%6.2f, z=(%.2f,%.2f,%.2f)' % \
                    sum(((x,), (y,), tuple(z)), ())
        else:
            return 'x=%.2f, y=%.2f' % (x, y)

    ax.format_coord = format_coord

    if fig.canvas.toolbar is not None:
        # See https://stackoverflow.com/a/47086132
        def mouse_move(self, event):
            if event.inaxes and event.inaxes.get_navigate():
                s = event.inaxes.format_coord(event.xdata, event.ydata)
                self.set_message(s)

        def mouse_move_patch(arg):
            return mouse_move(fig.canvas.toolbar, arg)

        fig.canvas.toolbar._idDrag = fig.canvas.mpl_connect(
            'motion_notify_event', mouse_move_patch)

    attach_keypress(fig)
    attach_zoom(ax)

    if have_mpldc:
        mpldc.datacursor(display='single')

    if figp is None:
        fig.show()

    return fig, ax
コード例 #40
0
ファイル: plot.py プロジェクト: LordHui/sporco
def contour(z,
            x=None,
            y=None,
            v=5,
            xlog=False,
            ylog=False,
            xlbl=None,
            ylbl=None,
            title=None,
            cfmt=None,
            cfntsz=10,
            lfntsz=None,
            alpha=1.0,
            cmap=None,
            vmin=None,
            vmax=None,
            fgsz=None,
            fgnm=None,
            fig=None,
            ax=None):
    """
    Contour plot of a 2D surface. If a figure object is specified then the
    plot is drawn in that figure, and ``fig.show()`` is not called. The
    figure is closed on key entry 'q'.

    Parameters
    ----------
    z : array_like
        2d array of data to plot
    x : array_like, optional (default None)
        Values for x-axis of the plot
    y : array_like, optional (default None)
        Values for y-axis of the plot
    v : int or sequence of floats, optional (default 5)
        An int specifies the number of contours to plot, and a sequence
        specifies the specific contour levels to plot.
    xlog : boolean, optional (default False)
        Set x-axis to log scale
    ylog : boolean, optional (default False)
        Set y-axis to log scale
    xlbl : string, optional (default None)
        Label for x-axis
    ylbl : string, optional (default None)
        Label for y-axis
    title : string, optional (default None)
        Figure title
    cfmt : string, optional (default None)
        Format string for contour labels.
    cfntsz : int or None, optional (default 10)
        Contour label font size. No contour labels are displayed if
        set to 0 or None.
    lfntsz : int, optional (default None)
        Axis label font size. The default font size is used if set to None.
    alpha : float, optional (default 1.0)
        Underlying image display alpha value
    cmap : :class:`matplotlib.colors.Colormap`, optional (default None)
        Colour map for surface. If none specifed, defaults to cm.YlOrRd
    vmin, vmax : float, optional (default None)
        Set upper and lower bounds for the colour map (see the corresponding
        parameters of :meth:`matplotlib.axes.Axes.imshow`)
    fgsz : tuple (width,height), optional (default None)
        Specify figure dimensions in inches
    fgnm : integer, optional (default None)
        Figure number of figure
    fig : :class:`matplotlib.figure.Figure` object, optional (default None)
        Draw in specified figure instead of creating one
    ax : :class:`matplotlib.axes.Axes` object, optional (default None)
        Plot in specified axes instead of current axes of figure

    Returns
    -------
    fig : :class:`matplotlib.figure.Figure` object
      Figure object for this figure
    ax : :class:`matplotlib.axes.Axes` object
      Axes object for this plot
    """

    figp = fig
    if fig is None:
        fig = plt.figure(num=fgnm, figsize=fgsz)
        fig.clf()
        ax = fig.gca()
    elif ax is None:
        ax = fig.gca()

    if xlog:
        ax.set_xscale('log')
    if ylog:
        ax.set_yscale('log')

    if cmap is None:
        cmap = cm.YlOrRd

    if x is None:
        x = np.arange(z.shape[1])
    else:
        x = np.array(x)
    if y is None:
        y = np.arange(z.shape[0])
    else:
        y = np.array(y)
    xg, yg = np.meshgrid(x, y)

    cntr = ax.contour(xg, yg, z, v, colors='black')
    kwargs = {}
    if cfntsz is not None and cfntsz > 0:
        kwargs['fontsize'] = cfntsz
    if cfmt is not None:
        kwargs['fmt'] = cfmt
    if kwargs:
        plt.clabel(cntr, inline=True, **kwargs)
    pc = ax.pcolormesh(xg,
                       yg,
                       z,
                       cmap=cmap,
                       vmin=vmin,
                       vmax=vmax,
                       alpha=alpha,
                       shading='gouraud',
                       clim=(vmin, vmax))

    if xlog:
        ax.fmt_xdata = lambda x: "{: .2e}".format(x)
    else:
        ax.fmt_xdata = lambda x: "{: .2f}".format(x)
    if ylog:
        ax.fmt_ydata = lambda x: "{: .2e}".format(x)
    else:
        ax.fmt_ydata = lambda x: "{: .2f}".format(x)

    if title is not None:
        ax.set_title(title)
    if xlbl is not None:
        ax.set_xlabel(xlbl, fontsize=lfntsz)
    if ylbl is not None:
        ax.set_ylabel(ylbl, fontsize=lfntsz)

    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.2)
    plt.colorbar(pc, ax=ax, cax=cax)

    attach_keypress(fig)
    attach_zoom(ax)

    if have_mpldc:
        mpldc.datacursor()

    if figp is None:
        fig.show()

    return fig, ax
コード例 #41
0
ファイル: plot.py プロジェクト: LordHui/sporco
def plot(y,
         x=None,
         ptyp='plot',
         xlbl=None,
         ylbl=None,
         title=None,
         lgnd=None,
         lglc=None,
         **kwargs):
    """
    Plot points or lines in 2D. If a figure object is specified then the
    plot is drawn in that figure, and ``fig.show()`` is not called. The
    figure is closed on key entry 'q'.

    Parameters
    ----------
    y : array_like
        1d or 2d array of data to plot. If a 2d array, each column is
        plotted as a separate curve.
    x : array_like, optional (default None)
        Values for x-axis of the plot
    ptyp : string, optional (default 'plot')
        Plot type specification (options are 'plot', 'semilogx',
        'semilogy', and 'loglog')
    xlbl : string, optional (default None)
        Label for x-axis
    ylbl : string, optional (default None)
        Label for y-axis
    title : string, optional (default None)
        Figure title
    lgnd : list of strings, optional (default None)
        List of legend string
    lglc : string, optional (default None)
        Legend location string
    **kwargs :  :class:`matplotlib.lines.Line2D` properties or figure \
    properties, optional
        Keyword arguments specifying :class:`matplotlib.lines.Line2D`
        properties, e.g. ``lw=2.0`` sets a line width of 2, or properties
        of the figure and axes. If not specified, the defaults for line
        width (``lw``) and marker size (``ms``) are 1.5 and 6.0
        respectively. The valid figure and axes keyword arguments are
        listed below:

        .. |mplfg| replace:: :class:`matplotlib.figure.Figure` object
        .. |mplax| replace:: :class:`matplotlib.axes.Axes` object

        .. rst-class:: kwargs

        =====  ==================== ======================================
        kwarg  Accepts              Description
        =====  ==================== ======================================
        fgsz   tuple (width,height) Specify figure dimensions in inches
        fgnm   integer              Figure number of figure
        fig    |mplfg|              Draw in specified figure instead of
                                    creating one
        ax     |mplax|              Plot in specified axes instead of
                                    current axes of figure
        =====  ==================== ======================================


    Returns
    -------
    fig : :class:`matplotlib.figure.Figure` object
      Figure object for this figure
    ax : :class:`matplotlib.axes.Axes` object
      Axes object for this plot
    """

    # Extract kwargs entries that are not related to line properties
    fgsz = kwargs.pop('fgsz', None)
    fgnm = kwargs.pop('fgnm', None)
    fig = kwargs.pop('fig', None)
    ax = kwargs.pop('ax', None)

    figp = fig
    if fig is None:
        fig = plt.figure(num=fgnm, figsize=fgsz)
        fig.clf()
        ax = fig.gca()
    elif ax is None:
        ax = fig.gca()

    # Set defaults for line width and marker size
    if 'lw' not in kwargs and 'linewidth' not in kwargs:
        kwargs['lw'] = 1.5
    if 'ms' not in kwargs and 'markersize' not in kwargs:
        kwargs['ms'] = 6.0

    if ptyp not in ('plot', 'semilogx', 'semilogy', 'loglog'):
        raise ValueError("Invalid plot type '%s'" % ptyp)
    pltmth = getattr(ax, ptyp)
    if x is None:
        pltln = pltmth(y, **kwargs)
    else:
        pltln = pltmth(x, y, **kwargs)

    ax.fmt_xdata = lambda x: "{: .2f}".format(x)
    ax.fmt_ydata = lambda x: "{: .2f}".format(x)

    if title is not None:
        ax.set_title(title)
    if xlbl is not None:
        ax.set_xlabel(xlbl)
    if ylbl is not None:
        ax.set_ylabel(ylbl)
    if lgnd is not None:
        ax.legend(lgnd, loc=lglc)

    attach_keypress(fig)
    attach_zoom(ax)

    if have_mpldc:
        mpldc.datacursor(pltln)

    if figp is None:
        fig.show()

    return fig, ax
コード例 #42
0
"""
An example of how to customize the keyboard shortcuts.
By default mpldatacursor will use "t" to toggle interactivity and "d" to 
hide/delete annotation boxes.
"""
import matplotlib.pyplot as plt
from mpldatacursor import datacursor

fig, ax = plt.subplots()
ax.plot(range(10), 'bo-')
ax.set_title('Press "e" to enable/disable the datacursor\n'
             'Press "h" to hide any annotation boxes')

dc = datacursor(keybindings=dict(hide='h', toggle='e'))

plt.show()
コード例 #43
0
import numpy as np
import matplotlib.pyplot as plt
import mpldatacursor

x, y, z = np.random.random((3, 10))
fig, ax = plt.subplots()
ax.scatter(x, y, c=z, s=100 * np.random.random(10))
mpldatacursor.datacursor()
plt.show()
コード例 #44
0
def _plot_clusters(estimator, fdatagrid, fig, ax, nrows, ncols, labels,
                   sample_labels, cluster_colors, cluster_labels,
                   center_colors, center_labels, colormap):
    """Implementation of the plot of the FDataGrid samples by clusters.

    Args:
        estimator (BaseEstimator object): estimator used to calculate the
            clusters.
        fdatagrid (FDataGrd object): contains the samples which are grouped
            into different clusters.
        fig (figure object): figure over which the graphs are plotted in
            case ax is not specified. If None and ax is also None, the figure
            is initialized.
        ax (list of axis objects): axis over where the graphs are plotted.
            If None, see param fig.
        nrows(int): designates the number of rows of the figure to plot the
            different dimensions of the image. Only specified if fig and
            ax are None.
        ncols(int): designates the number of columns of the figure to plot
            the different dimensions of the image. Only specified if fig
            and ax are None.
        labels (numpy.ndarray, int: (nsamples, ndim_image)): 2-dimensional
            matrix where each row contains the number of cluster cluster
            that observation belongs to.
        sample_labels (list of str): contains in order the labels of each sample
            of the fdatagrid.
        cluster_colors (list of colors): contains in order the colors of each
            cluster the samples of the fdatagrid are classified into.
        cluster_labels (list of str): contains in order the names of each
            cluster the samples of the fdatagrid are classified into.
        center_colors (list of colors): contains in order the colors of each
            centroid of the clusters the samples of the fdatagrid are classified into.
        center_labels list of colors): contains in order the labels of each
            centroid of the clusters the samples of the fdatagrid are classified into.
        colormap(colormap): colormap from which the colors of the plot are taken.

    Returns:
        (tuple): tuple containing:

            fig (figure object): figure object in which the graphs are plotted in case ax is None.

            ax (axes object): axes in which the graphs are plotted.
    """
    fig, ax = fdatagrid.generic_plotting_checks(fig, ax, nrows, ncols)

    _plot_clustering_checks(estimator, fdatagrid, None, sample_labels,
                            cluster_colors, cluster_labels, center_colors,
                            center_labels)

    if sample_labels is None:
        sample_labels = [
            '$SAMPLE: {}$'.format(i) for i in range(fdatagrid.nsamples)
        ]

    if cluster_colors is None:
        cluster_colors = colormap(
            np.arange(estimator.n_clusters) / (estimator.n_clusters - 1))

    if cluster_labels is None:
        cluster_labels = [
            '$CLUSTER: {}$'.format(i) for i in range(estimator.n_clusters)
        ]

    if center_colors is None:
        center_colors = ["black"] * estimator.n_clusters

    if center_labels is None:
        center_labels = [
            '$CENTER: {}$'.format(i) for i in range(estimator.n_clusters)
        ]

    colors_by_cluster = cluster_colors[labels]

    patches = []
    for i in range(estimator.n_clusters):
        patches.append(
            mpatches.Patch(color=cluster_colors[i], label=cluster_labels[i]))

    for j in range(fdatagrid.ndim_image):
        for i in range(fdatagrid.nsamples):
            ax[j].plot(fdatagrid.sample_points[0],
                       fdatagrid.data_matrix[i, :, j],
                       c=colors_by_cluster[i],
                       label=sample_labels[i])
        for i in range(estimator.n_clusters):
            ax[j].plot(fdatagrid.sample_points[0],
                       estimator.cluster_centers_.data_matrix[i, :, j],
                       c=center_colors[i],
                       label=center_labels[i])
        ax[j].legend(handles=patches)
        datacursor(formatter='{label}'.format)

    fdatagrid.set_labels(fig, ax)

    return fig, ax
コード例 #45
0
ファイル: wcs_viewer.py プロジェクト: raphaelrpl/wcsviewer
    def get_coverage(self):
        if not self.wcs:
            QMessageBox.information(self.iface.mainWindow(), "Error", "Set configuration on \"Configuration\" tab")
            return
        wcs_params = {}
        rangesubset = self.dlg.bandsInput.text()

        col_min, col_max = self.dlg.colMin.text(), self.dlg.colMax.text()
        row_min, row_max = self.dlg.rowMin.text(), self.dlg.rowMax.text()

        if rangesubset:
            wcs_params['rangesubset'] = rangesubset
            print("OI")
            # self.wcs.get_coverage(coverage_id=self.dlg.comboCoverage.currentText(), rangesubset=rangesubset)
        print("FORA OI")
        start_date = self.dlg.startDateInput.text() or self.start_date
        end_date = self.dlg.endDateInput.text() or self.end_date

        wcs_params['subset'] = [
            "col_id(%s,%s)" % (str(col_min), str(col_max)),
            "row_id(%s,%s)" % (str(row_min), str(row_max)),
            "time_id(%s,%s)" % (str(start_date), str(end_date))]
        print("PARAMS SUBSET")

        self.wcs.get_coverage(coverage_id=self.dlg.comboCoverage.currentText(), **wcs_params)
        print("GETADO")
        self.dlg.dataOutput.setText("")
        self.dlg.dataOutput.append(self.wcs.values)

        data_strings = ""

        elements = self.wcs.values.split(',')
        bands_values = [e.lstrip().split(' ') for e in elements]

        bands_it = len(elements[0].split(' '))

        # plot (use with subplot)
        # figure = plt.figure()

        begin_date = parser.parse(start_date)
        final_date = parser.parse(end_date)
        dates = []
        period = int(self.wcs.period)

        while begin_date <= final_date:
            dates.append(begin_date)
            begin_date += timedelta(days=period)

        import matplotlib.dates as mdates
        print(dates)

        for i in xrange(bands_it):
            array = []
            for element in bands_values:
                array.append(int(element[i]))
                data_strings += element[i].lstrip()
            fact, remainder = divmod(len(array), len(dates))
            if not remainder:
                dts = sorted(dates * fact)
                plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
                # plt.gca().xaxis.set_major_locator(mdates.DayLocator())
                plt.plot(dts, array)
                plt.gcf().autofmt_xdate()
            else:
                plt.plot(array, marker='o')
            # Uncomment next lines to enable one graph per band
            # ax = figure.add_subplot(bands_it, 1, i)
            # ax.set_title('b1')
            # plt.plot(array)

        datacursor(hover=True)
        self.dlg.dataOutput.setText(data_strings)
        plt.show()
コード例 #46
0
def bode_joaco(datos,mode,spice_filename ,output_filename):
    master_spice_data = read_file_spice("input/spice_data/" + spice_filename)

    # freq_arr = np.asarray(spice_data["f"])
    # abs_arr = np.asarray(spice_data["abs"])
    # pha_arr = np.asarray(spice_data["pha"])
    #
    # freq_arr.shape = (len(freq_arr),1)
    # abs_arr.shape = (len(abs_arr), 1)
    # pha_arr.shape = (len(pha_arr), 1)
    # mat_aux = np.column_stack((freq_arr, abs_arr,pha_arr))
    # mat_aux.sort(axis=0)
    #
    # spice_data_aux = dict()
    # spice_data_aux["f"] = []
    # spice_data_aux["abs"] = []
    # spice_data_aux["pha"] = []
    # for i in range (len(freq_arr)):
    #     spice_data_aux["f"].append(freq_arr[i])
    # for i in range(len(abs_arr)):
    #     spice_data_aux["abs"].append(abs_arr[i])
    # for i in range(len(pha_arr)):
    #     spice_data_aux["pha"].append(pha_arr[i])
    #
    # spice_data=spice_data_aux

    for j in range(len(master_spice_data)):
        spice_data=master_spice_data[j]

        # for i in range(len(spice_data["pha"])):
        #     if spice_data["f"][i] < 9 :
        #         spice_data["pha"][i] = spice_data["pha"][i]+360
        #     spice_data["pha"][i] -= 360

        if mode == "mag":
            ax1.semilogx(spice_data["f"], spice_data["abs"], "magenta", linewidth=0.1, alpha=0.9)
        else:
            ax1.semilogx(spice_data["f"], spice_data["pha"], "magenta", linewidth=2.5, alpha=0.9)

        ### Real

        if mode == "mag":
            ax1.set_title('Diagrama de Bode (Módulo)')
            ax1.semilogx(datos["f"], datos["abs"], "cyan", linewidth=1, alpha=1)
            ax1.set_xlabel('Frecuencia (Hz)', fontsize=10)
            ax1.set_ylabel('|H(s)|db', fontsize=10)
            #ax1.semilogx(f, mag,"darkblue",linewidth=1, alpha=1)

        else:
            ax1.set_title('Diagrama de Bode (Fase)')
            ax1.semilogx(datos["f"], datos["pha"], "cyan", linewidth=1, alpha=1)
            ax1.set_xlabel('Frecuencia (Hz)', fontsize=10)
            ax1.set_ylabel('Fase (grados)', fontsize=10)
            #ax1.semilogx(f, phase, "darkblue",linewidth=1, alpha=1)

    blue_patch = mpatches.Patch(color='magenta', label='Simulación')
    green_patch = mpatches.Patch(color='cyan', label='Práctica')
    #red_patch = mpatches.Patch(color='darkblue', label='Teórico')
    #plt.legend(handles=[green_patch, blue_patch, red_patch])
    plt.legend(handles=[green_patch, blue_patch])

    ax1.minorticks_on()
    ax1.grid(which='major', linestyle='-', linewidth=0.3, color='black')
    ax1.grid(which='minor', linestyle=':', linewidth=0.1, color='black')
#   datacursor(display='multiple',formatter="Frec: {x:.3e}  Hz \nAmp:{y:.1f}dB".format, draggable=True)
    datacursor(display='multiple', tolerance=10, formatter="Frec: {x:.3e}  Hz \nAmp:{y:.1f} dB".format,draggable=True)
    plt.show()
    input("Press Enter ")

    fig.savefig("output/dataset1/" + output_filename, dpi=300)
    plt.cla()
    plt.close()
コード例 #47
0
ファイル: prim_box.py プロジェクト: yjx4131/PRIM
    def show_tradeoff(self):
        """Plot the tradeoff between coverage and density.
        
        Generates a plot of the tradeoff between coverage and density for the
        peeling/pasting trajectories.  Color is used to denote the number of
        restricted dimensions.
        
        Returns
        -------
        the Matplotlib figure
        """
        fig = plt.figure()
        ax = fig.add_subplot(111, aspect='equal')

        # setup the color map for coloring the number of restricted dimensions
        cmap = mpl.cm.YlGnBu_r  #@UndefinedVariable
        boundaries = np.arange(-0.5,
                               max(self.peeling_trajectory['res dim']) + 1.5,
                               step=1)
        ncolors = cmap.N
        norm = mpl.colors.BoundaryNorm(boundaries, ncolors)

        # plot the tradeoff
        p = ax.scatter(self.peeling_trajectory['coverage'],
                       self.peeling_trajectory['density'],
                       c=self.peeling_trajectory['res dim'],
                       norm=norm,
                       cmap=cmap,
                       picker=True)

        ax.set_ylabel('Density')
        ax.set_xlabel('Coverage')
        ax.set_ylim(0, 1.2)
        ax.set_xlim(0, 1.2)

        ticklocs = np.arange(0,
                             max(self.peeling_trajectory['res dim']) + 1,
                             step=1)
        cb = fig.colorbar(p, spacing='uniform', ticks=ticklocs, drawedges=True)
        cb.set_label("# of Restricted Dimensions")

        # enable mouse interaction
        def handle_click(event):
            if hasattr(event, "ind"):
                i = event.ind[0]
                self.select(i)
                self.show_details().show()

        def formatter(**kwargs):
            i = kwargs.get("ind")[0]
            data = self.peeling_trajectory.ix[i]
            return (
                ("Box %d\n" + "Coverage: %2.1f%%\n" + "Density: %2.1f%%\n" +
                 "Mass: %2.1f%%\n" + "Res Dim: %d") %
                (i, 100 * data["coverage"], 100 * data["density"],
                 100 * data["mass"], data["res dim"]))

        mpldatacursor.datacursor(formatter=formatter, hover=True)
        fig.canvas.mpl_connect('pick_event', handle_click)

        # enable tooltips on IPython Notebook
        if mpld3:
            css = """
            table {
              border-collapse: collapse;
            }
            
            th {
              background-color:  rgba(255,255,255,0.95);
            }
            
            td {
              background-color: rgba(255,255,255,0.95);
            }
            
            table, th, td {
              font-family:Tahoma, Tahoma, sans-serif;
              font-size: 16px;
              border: 1px solid black;
              text-align: right;
            }
            """

            labels = []
            columns_to_include = ['coverage', 'density', 'mass', 'res dim']
            frmt = lambda x: '{:.2f}'.format(x)

            for i in range(len(self.peeling_trajectory['coverage'])):
                label = self.peeling_trajectory.ix[[i], columns_to_include]
                label.columns = ["Coverage", "Density", "Mass", "Res. Dim."]
                label = label.T
                label.columns = ["Box {0}".format(i)]
                labels.append(str(label.to_html(float_format=frmt)))

            tooltip = mpld3.plugins.PointHTMLTooltip(p,
                                                     labels,
                                                     voffset=10,
                                                     hoffset=10,
                                                     css=css)
            mpld3.plugins.connect(fig, tooltip)

        return fig
コード例 #48
0
ファイル: cproj.py プロジェクト: chan-y-park/cproj
def plot_coxeter_projection(
    sage_data_str, root_system=None, n_of_v_0=None, weight_index=None,
    is_interactive=True, image_format=None,
):
    import matplotlib
    if is_interactive:
        matplotlib.use('TkAgg')
    else:
        matplotlib.use('Agg')
    import mpldatacursor
    import matplotlib.pyplot as pyplot

    if not is_interactive:
        pyplot.clf()

    # Unpack data from the sage script.
    data = eval(sage_data_str)
    weyl_orbit_strs = data["weyl_orbit_strs"]
    W_critical = data["W_critical"]
    root_strs = data["root_strs"]
    simple_soliton_table = data["simple_soliton_table"]
    v_c = data["coxeter_vector"]

    weyl_orbit = [eval(v_str) for v_str in weyl_orbit_strs]
    roots = [eval(r_str) for r_str in root_strs]

    title = root_system + "_" + str(n_of_v_0)

    max_n_digits = ceil(log10(len(weyl_orbit)))

    # Plot a figure of the projection of the soliton polytope.
    figure_size = 6 * max_n_digits
    figure = pyplot.figure(
        title, facecolor='w',
        figsize=(figure_size, figure_size), 
    )
    pyplot.axis('off')

    pyplot.axes().set_aspect('equal')

    mpldatacursor_artists = []

    # Plot critical points.
    W_marker_size = 25
    W_font_size = 18.0 / max_n_digits
    W_point_labels = ["$v_{{{}}} = {}$".format(i, v_i) 
                      for i, v_i in enumerate(weyl_orbit)]

    grouped_W_c = group_degenerate_W_c(W_critical)
    for W, indices in grouped_W_c:
        mplobjs = pyplot.plot(
            W.real, W.imag,
            'o',
            markersize=W_marker_size,
            markeredgewidth=1.5,
            markerfacecolor='w',
            color='k',
            label=', '.join(W_point_labels[i] for i in indices),
        )
        pyplot.text(
            W.real, W.imag,
            ','.join(str(i + 1) for i in indices),
            fontsize=W_font_size/len(indices),
            verticalalignment='center',
            horizontalalignment='center',
        )

        if is_interactive:
            mpldatacursor_artists.append(mplobjs[0])

    # Plot solitons connecting critical points.
    soliton_colormap = matplotlib.cm.ScalarMappable(
        norm=matplotlib.colors.Normalize(vmin=0, vmax=len(roots)),
        cmap=matplotlib.cm.get_cmap('jet'), 
    )
    soliton_colors = [soliton_colormap.to_rgba(i)
                      for i in range(len(roots))]
    random.shuffle(soliton_colors)

    if (weight_index is None 
        or weight_index > len(weyl_orbit) 
        or weight_index < 1):
        i_list = range(len(weyl_orbit))
    else:
        i_list = [weight_index-1]

    for i in i_list:
        W_i = W_critical[i]
        for j in range(len(weyl_orbit)):
            soliton_data = simple_soliton_table[i][j]
            if soliton_data is None:
                continue
            else:
                soliton, sign = soliton_data
            W_j = W_critical[j]
            if sign == -1:
                sign_str = '-'
            else:
                sign_str = ''
            root = tuple([sign*r_k for r_k in roots[soliton]])
            label = "${}\\alpha_{{{}}} = {}$".format(
                sign_str, soliton, root
            )

            offset = .05 / max_n_digits
            x = W_i.real
            y = W_i.imag
            dx = W_j.real - x
            dy = W_j.imag - y
            r = sqrt(dx**2 + dy**2)
            mplobjs = pyplot.arrow(
                x + (offset * dx)/r, 
                y + (offset * dy)/r, 
                (1 - 2*offset/r)*dx, 
                (1 - 2*offset/r)*dy, 
                length_includes_head=True,
                label=label, color=soliton_colors[soliton],
            )

            mpldatacursor_artists.append(mplobjs)

    mpldatacursor.datacursor(
        artists=mpldatacursor_artists,
        formatter="{label}".format,
        display="multiple",
        draggable=True,
    )

    pyplot.margins(.05)

    if is_interactive is True:
        matplotlib.rcParams["savefig.directory"] = "./"
        # Display the plot.
        pyplot.show()
    else:
        # Return the plot to web frontend.
        img = BytesIO()
        pyplot.savefig(img, format=image_format)
        img.seek(0)
        return img
コード例 #49
0
def remoteGene(gene):
    global Transcript_Annotations_File
    global ExonRegion_File
    global Selected_Gene
    global Prt_Trans_File
    global Prt_Regions_File
    global Prt_Boundaries_File
    global Etc_File
    import unique
    Selected_Gene = gene
    ExonRegion_File = unique.filepath("ExonViewFiles/Hs_Ensembl_exon.txt")
    Transcript_Annotations_File = unique.filepath(
        "ExonViewFiles/Hs_Ensembl_transcript-annotations.txt")
    Prt_Trans_File = unique.filepath(
        "ExonViewFiles/Hs_Ensembl_Protein__65_37.txt")
    Prt_Regions_File = unique.filepath(
        "ExonViewFiles/Hs_ProteinFeatures_build_65_37.txt")
    Prt_Boundaries_File = unique.filepath(
        "ExonViewFiles/Hs_ProteinCoordinates_build_65_37.tab")
    Etc_File = unique.filepath(
        "ExonViewFiles/Hs_RNASeq_K562_SRSF2_P95mut_vs_K562_SRSF2_WT.ExpCutoff-5.0_average-splicing-index-ProcessedSpliceData.txt"
    )
    #"ENSG00000005801"
    #"ENSG00000110514"
    total_val = ProteinCentricIsoformView(Selected_Gene)
    junctions = total_val[0]
    p_boundaries = total_val[1]
    p_domains = total_val[2]
    transcript_db = total_val[3]
    exon_db = total_val[4]
    splice_db = total_val[5]

    #for i in exon_db["ENST00000349238"]:
    #    print(i[2].EnsemblRegion())

    domain_color_list = []
    for i in p_domains:
        ploy = p_domains[i]
        for a in ploy:
            domain_color_list.append(a[1])

    domain_color_list = list(set(domain_color_list))
    domain_color_key = {}
    c_color1 = [0.8, 0.6, 0.1]
    c_color2 = [0.1, 0.6, 0.8]
    c_color3 = [0.6, 0.1, 0.8]
    c_color4 = [0.95, 0.6, 0.3]
    c_color5 = [0.3, 0.6, 0.95]
    c_color6 = [0.6, 0.3, 0.95]
    FLAG = 1

    for item in domain_color_list:
        if (FLAG == 1):
            domain_color_key[item] = c_color1
            FLAG = FLAG + 1
            continue
        if (FLAG == 2):
            domain_color_key[item] = c_color2
            FLAG = FLAG + 1
            continue
        if (FLAG == 3):
            domain_color_key[item] = c_color3
            FLAG = FLAG + 1
            continue
        if (FLAG == 4):
            domain_color_key[item] = c_color4
            FLAG = FLAG + 1
            continue
        if (FLAG == 5):
            domain_color_key[item] = c_color5
            FLAG = FLAG + 1
            continue
        if (FLAG == 6):
            domain_color_key[item] = c_color6
            FLAG = 1
            continue

    for i in domain_color_key:
        print(i, domain_color_key[i], "\n")

    Y = 50
    Transcript_to_Y = {}
    for transcript in transcript_db:
        Transcript_to_Y[transcript] = Y
        Y = Y + 200
    import traceback

    ylim = Y + 200
    currentAxis = plt.gca()
    ax = plt.axes()
    X_Pos_List = []
    for transcript in transcript_db:
        try:
            Junc_List = junctions[transcript]
            y_pos = Transcript_to_Y[transcript]
            Gene_List = exon_db[transcript]
            color_flag = 1
            for entry in Gene_List:
                G_start = entry[0][0]
                G_end = entry[0][1]
                Exon_Object = entry[2]
                try:
                    LabelClass = splice_db[Exon_Object.EnsemblRegion()]
                    ExonName = Exon_Object.EnsemblExon()
                    RegCall = LabelClass.RegCall()
                    SplicingIndex = LabelClass.SplicingIndex()
                    PVal = LabelClass.PVal()
                    Midas = LabelClass.Midas()
                    Label = "\n" + "Exon: " + str(
                        ExonName) + "\n" + "RegCall: " + str(
                            RegCall) + "\n" + "Splicing Index: " + str(
                                SplicingIndex) + "\n" + "P-Value: " + str(
                                    PVal) + "\n" + "Midas Value: " + str(Midas)
                    if (RegCall == "UC"):
                        color_choice = "Grey"
                    else:
                        S_Int = float(SplicingIndex)
                        if (S_Int > 0):
                            color_choice = (0.7, 0.7, 0.99)
                        if (S_Int < 0):
                            color_choice = (0.8, 0.4, 0.4)

                except:
                    #print(traceback.format_exc());sys.exit()
                    Label = ""
                    color_choice = "Grey"
                #print("Start", G_start, "end", G_end, "Region", entry[2].EnsemblRegion())
                if ((color_flag % 2) == 0):
                    currentAxis.add_patch(
                        Rectangle((G_start, y_pos), (G_end - G_start),
                                  50,
                                  color=color_choice,
                                  label=(entry[2].EnsemblRegion() + Label)))
                if ((color_flag % 2) != 0):
                    currentAxis.add_patch(
                        Rectangle((G_start, y_pos), (G_end - G_start),
                                  50,
                                  color=color_choice,
                                  label=(entry[2].EnsemblRegion() + Label)))
                color_flag = color_flag + 1

            for entry in Junc_List:
                try:
                    LabelClass = splice_db[entry[2]]
                    RegCall = LabelClass.RegCall()
                    SplicingIndex = LabelClass.SplicingIndex()
                    PVal = LabelClass.PVal()
                    Midas = LabelClass.Midas()
                    Label = "\n" + "RegCall: " + str(
                        RegCall) + "\n" + "Splicing Index: " + str(
                            SplicingIndex) + "\n" + "P-Value: " + str(
                                PVal) + "\n" + "Midas Value: " + str(Midas)
                    if (float(SplicingIndex) > 0):
                        color_junc = "blue"
                    if (float(SplicingIndex) < 0):
                        color_junc = "red"
                    if (RegCall == "UC"):
                        color_junc = "grey"
                except:
                    Label = ""
                    color_junc = "grey"
                currentAxis.add_patch(
                    Rectangle((entry[0], y_pos), (entry[1] - entry[0]),
                              50,
                              color="White",
                              label=(str(entry[2]) + Label)))
                ax.arrow(entry[0], (y_pos + 50),
                         8,
                         40,
                         label=(str(entry[2]) + Label),
                         color=color_junc)
                ax.arrow((entry[0] + 8), (y_pos + 90),
                         11,
                         -40,
                         label=(str(entry[2]) + Label),
                         color=color_junc)

            P_Bound_List = p_boundaries[transcript]
            P_Domain_List = p_domains[transcript]
            E_Start = P_Bound_List[-2]
            E_End = P_Bound_List[-1]
            P_Start = P_Bound_List[1]
            P_End = P_Bound_List[2]
            #print("Boundaries: ", P_Start, P_End)
            X_Pos_List.append(int(E_End))
            #currentAxis.add_patch(Rectangle((E_Start, y_pos), E_End, 50, color = "Blue"))
            try:
                currentAxis.add_patch(
                    Rectangle((P_Start, (y_pos + 120)), (P_End - P_Start),
                              10,
                              label=("Protein: " + str(P_Bound_List[0]))))
            except:
                pass
            for entry in P_Domain_List:
                #print("Domain", entry)
                color_domain_choice = domain_color_key[entry[1]]
                currentAxis.add_patch(
                    Rectangle((entry[2], y_pos + 100), (entry[3] - entry[2]),
                              50,
                              color=color_domain_choice,
                              label=("Protein: " + str(entry[0]) + "\n" +
                                     "Domain: " + str(entry[1]))))
        except:
            continue
    plt.ylim([0.0, ylim])
    try:
        max_x = max(X_Pos_List)
    except:
        max_x = 5000
    try:
        plt.xlim([0.0, max_x])
    except:
        plt.xlim([0.0, 3000])
    datacursor(hover=True,
               formatter='{label}'.format,
               bbox=dict(fc='yellow', alpha=1),
               arrowprops=None)
    plt.show()
コード例 #50
0
            color='red')

    ax.plot(timepoints,
            diff_times,
            label='#time for statediff [ms]',
            color='black')

    ax2 = ax.twinx()
    ax2.plot(timepoints, online_players, label='#online players', color='b')
    ax2.plot(timepoints,
             changed_chunks,
             label='#changed chunks',
             linestyle='--',
             color='g')
    ax2.plot(timepoints,
             changed_tile_entities,
             label='#changed tile entities',
             linestyle='--',
             color='orange')

    # fix legend
    #lines, labels = ax.get_legend_handles_labels()
    #lines2, labels2 = ax2.get_legend_handles_labels()
    #ax.legend(lines + lines2, labels + labels2, loc=2)
    ax.legend(loc=2)  # upper left
    ax2.legend(loc=1)  # upper right

    ax.set(xlabel='Time', title='Status information')
    ax.grid()
    datacursor()
    plt.show()
コード例 #51
0
"""
A bar plot where each bar's height and name will be displayed above the top of
the bar when it is moused over.  This serves as an example of overriding the
x,y position of the "popup" annotation using the `props_override` option.
"""
import string
import matplotlib.pyplot as plt
from mpldatacursor import datacursor

fig, ax = plt.subplots()
ax.bar(range(9), range(1, 10), align='center')
labels = string.ascii_uppercase[:9]
ax.set(xticks=range(9), xticklabels=labels, title='Hover over a bar')

# By default, the "popup" annotation will appear at the mouse's position.
# Instead, you might want it to appear centered at the top of the rectangle in
# the bar plot. By changing the x and y values using the "props_override"
# option, we can customize where the "popup" appears.
def override(**kwargs):
    kwargs['x'] = kwargs['left'] + 0.5 * kwargs['width']
    kwargs['y'] = kwargs['bottom'] + kwargs['height']
    kwargs['label'] = labels[int(kwargs['x'])]
    return kwargs

datacursor(hover=True, xytext=(0, 20), props_override=override,
           formatter='{label}: {height}'.format)

plt.show()
コード例 #52
0
def show_plot():
    plt.ioff()

    degree = 1

    register_matplotlib_converters()

    plt.rcParams['figure.figsize'] = [20, 15]

    years_fmt = mdates.DateFormatter('%Y-%m-%d')

    fig, ax = plt.subplots()

    dataset = data2

    dates = [y['upload_date'] for y in dataset]

    y_a = np.array([x['view_count'] for x in dataset])
    x_a = np.array([dd.timestamp() / 10000 for dd in dates])

    z, resid = np.polyfit(x_a, y_a, degree, full=True)[:2]

    #y_a_fit = np.polyval(z, x_a)
    #y_a_adj = y_a - y_a_fit

    p = np.poly1d(z)

    scats = []
    for v in dataset:
        y = v['view_count']
        x = v['upload_date']
        sc = ax.scatter(x,
                        y,
                        s=20,
                        label='{} | {} | {:,}'.format(v['title'],
                                                      x.strftime('%Y-%m-%d'),
                                                      y))

        scats.append(sc)

    ax.plot(dates, p(x_a), 'r--')

    ax.xaxis.set_major_formatter(years_fmt)
    ax.format_xdata = mdates.DateFormatter('%Y-%m-%d %H')

    fig.autofmt_xdate()

    plt.title('y = {0:.4f}(x) {2} {1:+.4f}  RSq: {3}'.format(
        round(z[0], 4), round(z[-1], 4), ' '.join([
            '{:+.4f}(x^{})'.format(round(fc, 4), ii + 2)
            for ii, fc in enumerate(z[1:-1])
        ]), round(1 - (resid / (y_a.size * y_a.var()))[0], 4)))
    plt.xlabel('date')
    plt.ylabel('views')

    plt.subplots_adjust(top=.94, bottom=.12, right=.98, left=.04)

    #plt.show()

    mpldatacursor.datacursor(scats,
                             formatter='{label}'.format,
                             keep_inside=True,
                             hover=True,
                             bbox={
                                 'boxstyle': 'round,pad=0.5',
                                 'fc': 'lightblue',
                                 'alpha': 0.95,
                                 'edgecolor': 'black'
                             })

    plt.ion()
コード例 #53
0
        "\\usepackage{siunitx}",         # load additional packages
        ]
}
mpl.rcParams.update(pgf_with_custom_preamble)
import matplotlib.pyplot as plt
from mpldatacursor import datacursor
plt.ion()
plt.close('all')

if __name__ == '__main__':
    costkeeping = np.load('costkeeping_bbb.npz')
    plt.figure()
    plt.plot(costkeeping['flexure'][0,:], costkeeping['flexure'][1,:], 'bo',
            label='flexure cost')
    plt.plot(costkeeping['shear'][0,:], costkeeping['shear'][1,:], 'r^',
            label='shear cost')
    plt.plot(costkeeping['deck'][0,:], costkeeping['deck'][1,:], 'gv',
            label='deck cost')
    plt.xlim((-1,101))
    plt.ylim((-1,8e7))

    plt.xlabel('strengthening time (year)', fontsize=12)
    plt.ylabel('cost (mm\\textsuperscript{3})', fontsize=12)

    ax = plt.gca()
    ax.ticklabel_format(axis='y', style='sci', scilimits=(-3,3))

    datacursor(formatter='{label}'.format,display='multiple', draggable=True,
            bbox=None, fontsize=12,
            arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k'))
コード例 #54
0
ファイル: PixelFinder.py プロジェクト: nellyBoi/latGIS
# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
import mpldatacursor

import sys
sys.path.append(
    r'c:\users\johnn\appdata\local\programs\python\python37-32\lib\site-packages'
)


class Formatter(object):
    def __init__(self, im):
        self.im = im

    def __call__(self, x, y):
        z = self.im.get_array()[int(y), int(x)]
        return 'x={:.01f}, y={:.01f}, z={:.01f}'.format(x, y, z)


data = np.random.random((10, 10))

fig, ax = plt.subplots()
im = ax.imshow(data, interpolation='none')
ax.format_coord = Formatter(im)
plt.show()

mpldatacursor.datacursor(hover=True, bbox=dict(alpha=1, fc='w'))
plt.show()
コード例 #55
0
ファイル: p_1d_plot.py プロジェクト: daringli/PERFECT_utils
def perfect_1d_plot(dirlist,attribs,xattr="psi",normname="norms.namelist",speciesname="species",psiN_to_psiname="psiAHat.h5",global_term_multiplier_name="globalTermMultiplier.h5",cm=cm.rainbow,lg=True,markers=None,linestyles=None,xlims=None,same_plot=False,outputname="default",ylabels=None,label_all=False,global_ylabel="",sort_species=True,first=["D","He"],last=["e"],generic_labels=True,label_dict={"D":"i","He":"z","N":"z","e":"e"},vlines=None,hlines=None,share_scale=[],interactive=False):
    #dirlist: list of simulation directories
    #attribs: list of fields to plot from simulation
    #speciesname: species filename in the simuldir
    #normname: norm filename in the simuldir
    #lg: controls whether to interpret nearby simulations as being paired
    
    if type(attribs) is not list:
        attribs=[attribs]
    if ylabels is not None:
        if type(ylabels) is not list:
            ylabels=[ylabels]*len(attribs)
        else:
            if len(ylabels) != len(attribs):
                print "p_1d_plot: error: ylabels not the same size as attribs"
                exit(1)
    else:
        ylabels=['']*len(attribs)
                
    
    normlist=[x + "/" + normname for x in dirlist]
    specieslist=[x + "/" + speciesname for x in dirlist]
    psiN_to_psiList=[x + "/" + psiN_to_psiname for x in dirlist]
    global_term_multiplierList=[x + "/" + global_term_multiplier_name for x in dirlist]
    simulList=perfect_simulations_from_dirs(dirlist,normlist,specieslist,psiN_to_psiList,global_term_multiplierList)
    if markers == None:
        markers=['']*len(simulList)

    #some logic to differentiate between species independent
    #and species quantities further down will fail if there are simulations
    #one species (which you really shouldn't do due to quasi-neutrality!!)
    num_species_array=numpy.array([len(simul.species) for simul in simulList])
    one_species_list=numpy.where(num_species_array<=1)
    if len(num_species_array[one_species_list])>0:
        print "p_1d_plot: warning: there are simulations with one (or) less species! Logic to determine whether attribute is a species property will not work."
        
    
    if generic_labels:
        for simul in simulList:
            simul.species_list=generic_species_labels(simul.species_list,label_dict)
            first=generic_species_labels(first,label_dict)
            last=generic_species_labels(last,label_dict)
    species_set=set([])
    for simul in simulList:
        species_set = species_set | set(simul.species)
    
    #print gridspec
    

    i=-1
    psp_lists=[] #list of lists of perfect subplot object
    gridspec_list=[]
    
    colors=cm(numpy.linspace(0,1,len(simulList)))
    #assign colors to simulations
    all_linecolors=[]
    color_index=0

    local=[simul.local for simul in simulList]
    noddpsi=[simul.no_ddpsi for simul in simulList]
    
    if lg:
        colors=cm(numpy.linspace(0,1,len(simulList)-sum(local)-sum(noddpsi)))
        if sum(local)>0:
            #if we have local simulations, increment color after them
            for loc in local:
                all_linecolors.append(colors[color_index])
                if loc == True:
                    color_index=color_index+1
        elif sum(noddpsi)>0:
            #otherwise, increment color after noddpsi simulation
            for nd in noddpsi:
                all_linecolors.append(colors[color_index])
                if nd == True:
                    color_index=color_index+1
        else:
            #else, always increment
            all_linecolors=cm(numpy.linspace(0,1,len(simulList)))
    else:
        # force always increment behavior
        all_linecolors=cm(numpy.linspace(0,1,len(simulList)))

    if linestyles == None:
        linestyles=[] #linestyles generated from local or global
        for n,l in zip(noddpsi,local):
            # local overrides noddpsi in code as well
            if l:
                linestyles=linestyles+["dashed"]
            elif n:
                linestyles=linestyles+["dashdot"]
            else:
                linestyles=linestyles+["solid"]
    
    for i_a,attrib in enumerate(attribs):
        psp_list=[]
        #check whether attribute is species dependent
        #it will be assumed to be if the lenght along the 1 axis
        #is equal to the number of species in a simulation for all simulations
        #at least as long as there is more than one species in the simulation.
        attrib_sp_dep = is_attribute_species_dependent(simulList,attrib)
        #we will assign data to the following attribute related groups
        attrib_groupname=attrib
        if attrib_sp_dep:
            species_attrib_groupname="species_dependent"
        else:
            species_attrib_groupname="species_independent"
        if same_plot:
            if i_a == len(attribs)-1:
                perhaps_last=True
            else:
                perhaps_last=False
        else:
            perhaps_last=True
        if sort_species:
            species_set=sort_species_list(list(species_set),first,last)
        if attrib_sp_dep:
            for i_sp,s in enumerate(species_set):
                i=i+1
                #data is taken for a given species for all simulations
                #index of species in simulation given by index to index
                index=[[ind for ind,spec in enumerate(simul.species) if spec==s] for simul in simulList]
                
                if all(len(ind)<=1 for ind in index):
                    data=[getattr(simul,attrib)[:,index[i_si][0]] for i_si,simul in enumerate(simulList) if s in simul.species]
                else:
                    print "p_1d_plot: warning: more than one of the same species in the simulation. Will add contributions."
                    data=[numpy.sum(getattr(simul,attrib)[:,index[i_si]],axis=1) for i_si,simul in enumerate(simulList) if s in simul.species]

                if xattr=="theta":
                    x_scale=1/numpy.pi
                else:
                    x_scale=1
                if xattr != None:
                    x=[getattr(simul,xattr)*x_scale for simul in simulList if s in simul.species]
                else:
                    # If xattrib is None, we plot against the index of the data
                    # This probably will not work if we are not plotting against
                    # the first index of data
                    x=[numpy.array(range(len(getattr(simul,attrib)))) for simul in simulList if s in simul.species]
                if xlims == None:
                    # min to max among all the simulations
                    xlims = [numpy.min(x),numpy.max(x)]
                    
                linecolors=[all_linecolors[i_si] for i_si,simul in enumerate(simulList) if s in simul.species]
                coordinates=(i,0)
                if perhaps_last and (i_sp == len(species_set) - 1):
                    last_groupname="last"
                    gridspec_list.append([i+1,1])
                else:
                    last_groupname="not_last"

                psp_list.append(perfect_subplot(data,x,subplot_coordinates=coordinates,groups=[s,attrib_groupname,species_attrib_groupname,last_groupname],linestyles=linestyles,colors=linecolors,markers=markers)) #yaxis_label=ylabels[i_a]
                

        else:
            i=i+1
            if perhaps_last:
                last_groupname="last"
                gridspec_list.append([i+1,1])
            else:
                last_groupname="not_last"
            #species independent plot
            data=[getattr(simul,attrib) for simul in simulList]
            x=[getattr(simul,xattr) for simul in simulList]
            linecolors=all_linecolors
            coordinates=(i,0)
            psp_list.append(perfect_subplot(data,x,subplot_coordinates=coordinates,groups=[attrib_groupname,species_attrib_groupname,last_groupname],linestyles=linestyles,colors=linecolors,markers=markers)) #yaxis_label=ylabels[i_a]
            
        
        psp_lists.append(psp_list)
        if not same_plot:
            i=-1

    #merge the psp_lists if everything is supposed to go in the same plot
    if same_plot:
        final_psp_lists=[]
        for psp_list in psp_lists:
            final_psp_lists = final_psp_lists + psp_list
        psp_lists=[final_psp_lists]
        
            
    for i_li,psp_list in enumerate(psp_lists):
        for psp in psp_list:
            print psp.groups
            psp.xlims=xlims
            psp.data=psp.data_inrange()
            psp.x=psp.x_inrange()
        if same_plot:
            attrib_groups=[perfect_subplot_group(psp_list,groups=[a]) for a in attribs]
            for ylabel,attrib_group in zip(ylabels,attrib_groups):
                if label_all:
                    attrib_group.setattrs("yaxis_label",ylabel)
                else:
                    attrib_group.set_middle_ylabel(ylabel)
        else:
            attrib_groups=[perfect_subplot_group(psp_list,groups=[a]) for a in [attribs[i_li]]]
            for ylabel,attrib_group in zip([ylabels[i_li]],attrib_groups):
                if label_all:
                    attrib_group.setattrs("yaxis_label",ylabel)
                else:
                    attrib_group.set_middle_ylabel(ylabel)
                if len(share_scale)>0:
                    share_scale_group=perfect_subplot_group(psp_list,groups=share_scale,logic="or")
                    share_scale_group.setattrs("ylims",[share_scale_group.get_min("data",margin=0.1),share_scale_group.get_max("data",margin=0.1)])
                    

                    
        
        species_groups=[perfect_subplot_group(psp_list,groups=[s]) for s in species_set]
        species_indep_groups=perfect_subplot_group(psp_list,groups=["species_independent"])
        local_group = perfect_subplot_group(psp_list,groups=["local"])
        global_group = perfect_subplot_group(psp_list,groups=["global"])
        last_group = perfect_subplot_group(psp_list,groups=["last"])
        all_group=perfect_subplot_group(psp_list,groups='',get_all=True)
        
        for species_group,s in zip(species_groups,species_set):
            species_group.setattrs("title",s)

        

        for attrib_group in attrib_groups:
            this_species_groups=[perfect_subplot_group(attrib_group.p_subplot_list,groups=[s]) for s in species_set]
            for this_species_group in this_species_groups:
                if len(this_species_group.p_subplot_list)>0:
                    this_species_group.setattrs("ylims",[this_species_group.get_min("data",margin=0.1),this_species_group.get_max("data",margin=0.1)])
                    #print [this_species_group.get_min("data",margin=0.1),this_species_group.get_max("data",margin=0.1)]
            this_species_indep_group=perfect_subplot_group(attrib_group.p_subplot_list,groups=["species_independent"])
            if len(this_species_indep_group.p_subplot_list)>0:
                this_species_indep_group.setattrs("ylims",[this_species_indep_group.get_min("data",margin=0.1),this_species_indep_group.get_max("data",margin=0.1)])
            this_share_scale_group=perfect_subplot_group(attrib_group.p_subplot_list,groups=share_scale,logic="or")
            if len(this_share_scale_group.p_subplot_list)>0:
                this_share_scale_group.setattrs("ylims",[this_share_scale_group.get_min("data",margin=0.1),this_share_scale_group.get_max("data",margin=0.1)])
            
            
        
            
        all_group.setattrs("show_yaxis_ticklabel",True)
        all_group.setattrs("vlines",vlines)
        all_group.setattrs("hlines",hlines)
        last_group.setattrs("show_xaxis_ticklabel",True)
        #print gridspec_list[i_li]
        if xattr=="psi":
            global_xlabel=r"$\psi_N$"
        elif xattr=="theta":
            global_xlabel=r"$\theta/\pi$"
        elif xattr=="sqrtpsi":
            global_xlabel=r"$\sqrt{\psi_N}$"
        elif xattr=="psiOverOrbitWidth":
            global_xlabel=r"$\sqrt{\psi_N}$"
        elif xattr=="actual_psi":
            global_xlabel=r"$\hat{\psi}$"
        elif xattr=="actual_psiN":
            global_xlabel=r"$\psi_N$"
        elif xattr=="psi_index":
            global_xlabel=r"$i_\psi$"
        elif xattr==None:
            global_xlabel=r"$i$"
        perfect_visualizer(psp_list,gridspec_list[i_li],global_xlabel=global_xlabel,dimensions=1,global_ylabel=global_ylabel)
        if same_plot:
            plt.savefig(outputname+".pdf")
        else:
            plt.savefig(attribs[i_li]+".pdf")
        if interactive:
            #dangerous, since it will (for some reason) be executed after all 1d_plot calls and show everything plotted in the given script.
            datacursor(display='multiple', draggable=True)
            plt.show()