Python matplotlib.pyplot 模块,subplot2grid() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.subplot2grid()

项目:software-suite-movie-market-analysis    作者:93lorenzo    | 项目源码 | 文件源码
def tsplot(y, lags=None, figsize=(10, 8), style='bmh'):
    if not isinstance(y, pd.Series):
        y = pd.Series(y)
    with plt.style.context(style):
        fig = plt.figure(figsize=figsize)
        # mpl.rcParams['font.family'] = 'Ubuntu Mono'
        layout = (3, 2)
        ts_ax = plt.subplot2grid(layout, (0, 0), colspan=2)
        acf_ax = plt.subplot2grid(layout, (1, 0))
        pacf_ax = plt.subplot2grid(layout, (1, 1))
        qq_ax = plt.subplot2grid(layout, (2, 0))
        pp_ax = plt.subplot2grid(layout, (2, 1))

        y.plot(ax=ts_ax)
        ts_ax.set_title('Time Series Analysis Plots')
        smt.graphics.plot_acf(y, lags=lags, ax=acf_ax, alpha=0.5)
        smt.graphics.plot_pacf(y, lags=lags, ax=pacf_ax, alpha=0.5)
        sm.qqplot(y, line='s', ax=qq_ax)
        qq_ax.set_title('QQ Plot')
        scs.probplot(y, sparams=(y.mean(), y.std()), plot=pp_ax)

        plt.tight_layout()
    return
项目:tfnn    作者:MorvanZhou    | 项目源码 | 文件源码
def __init__(self, grid_space, objects, evaluator, figsize, sleep=0.001):
        super(ScaleMonitor, self).__init__(evaluator, 'score_monitor')
        self._network = self.evaluator.network
        self._axes = {}
        self._tplot_axes = {}
        self._vplot_axes = {}
        self._fig = plt.figure(figsize=figsize)
        self._sleep = sleep
        for r_loc, name in enumerate(objects):
            r_span, c_span = 1, grid_space[1]
            self._axes[name] = plt.subplot2grid(grid_space, (r_loc, 0), colspan=c_span, rowspan=r_span)
            if name != objects[-1]:
                plt.setp(self._axes[name].get_xticklabels(), visible=False)
            self._axes[name].set_ylabel(r'$%s$' % name.replace(' ', r'\ ').capitalize())
        self._fig.subplots_adjust(hspace=0.1)
        plt.ion()
        plt.show()
项目:autoreject    作者:autoreject    | 项目源码 | 文件源码
def _prepare_projectors(params):
    """ Helper for setting up the projectors for epochs browser """
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    epochs = params['epochs']
    projs = params['projs']
    if len(projs) > 0 and not epochs.proj:
        ax_button = plt.subplot2grid((10, 15), (9, 14))
        opt_button = mpl.widgets.Button(ax_button, 'Proj')
        callback_option = partial(_toggle_options, params=params)
        opt_button.on_clicked(callback_option)
        params['opt_button'] = opt_button
        params['ax_button'] = ax_button

    # As here code is shared with plot_evoked, some extra steps:
    # first the actual plot update function
    params['plot_update_proj_callback'] = _plot_update_epochs_proj
    # then the toggle handler
    callback_proj = partial(_toggle_proj, params=params)
    # store these for use by callbacks in the options figure
    params['callback_proj'] = callback_proj
    callback_proj('none')
项目:finance-hacking    作者:wellsjo    | 项目源码 | 文件源码
def graphRawFX():
    date, bid, ask = np.loadtxt('data/GBPUSD1d.txt',
            unpack=True,
            delimiter=',',
            converters={0: mdates.strpdate2num('%Y%m%d%H%M%S')}
            )
    fig = plt.figure(figsize=(10,7))
    ax1 = plt.subplot2grid((40, 40), (0, 0), rowspan=40, colspan=40)
    ax1.plot(date, bid)
    ax1.plot(date, ask)
    plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))

    for label in ax1.xaxis.get_ticklabels():
        label.set_rotation(45)

    ax1_2 = ax1.twinx()
    ax1_2.fill_between(date, 0, (ask-bid), facecolor='g', alpha=.3)

    plt.subplots_adjust(bottom=.23)

    plt.grid(True)
    plt.show()
项目:decoding_challenge_cortana_2016_3rd    作者:kingjr    | 项目源码 | 文件源码
def _prepare_projectors(params):
    """ Helper for setting up the projectors for epochs browser """
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    epochs = params['epochs']
    projs = params['projs']
    if len(projs) > 0 and not epochs.proj:
        ax_button = plt.subplot2grid((10, 15), (9, 14))
        opt_button = mpl.widgets.Button(ax_button, 'Proj')
        callback_option = partial(_toggle_options, params=params)
        opt_button.on_clicked(callback_option)
        params['opt_button'] = opt_button
        params['ax_button'] = ax_button

    # As here code is shared with plot_evoked, some extra steps:
    # first the actual plot update function
    params['plot_update_proj_callback'] = _plot_update_epochs_proj
    # then the toggle handler
    callback_proj = partial(_toggle_proj, params=params)
    # store these for use by callbacks in the options figure
    params['callback_proj'] = callback_proj
    callback_proj('none')
项目:Buffe    作者:bentzinir    | 项目源码 | 文件源码
def __init__(self):

        game_params = {
            'L': 5,
            'dt': 0.15,
            'v_0': 0.,
            'v_max': 0.5,
        }

        self._connect(game_params)

        self._train_params()

        self.fig = plt.figure()
        self.ax = plt.subplot2grid((2, 2), (0, 0), colspan=2, rowspan=2)

        plt.ion()
        plt.show()
项目:Differential-Algebra-Tracker    作者:OscarES    | 项目源码 | 文件源码
def plot_x_before_and_after(multipartin, multipartout):

    xin = [multipartin[i][0][0] for i in xrange(len(multipartin))]
    xpin = [multipartin[i][0][1] for i in xrange(len(multipartin))]

    xo = [multipartout[i][0][0] for i in xrange(len(multipartout))]
    xpo = [multipartout[i][0][1] for i in xrange(len(multipartout))]

    matplotlib.rcParams.update({'font.size': 31})
    plt.figure(0)

    ax1 = plt.subplot2grid((1,2), (0,0))
    ax1.plot(xin,xpin,'ro', zorder=1)
    plt.title('Initial values in x')
    plt.xlabel('x [m]')
    plt.ylabel('x\' []')

    ax2 = plt.subplot2grid((1,2), (0,1))
    ax2.plot(xo,xpo,'ro', zorder=1)
    plt.title('Values after lattice in x')
    plt.xlabel('x [m]')
    plt.ylabel('x\' []')

    plt.show()
项目:Differential-Algebra-Tracker    作者:OscarES    | 项目源码 | 文件源码
def plot_x_after(multipartout):
    xo = [multipartout[i][0][0] for i in xrange(len(multipartout))]
    xpo = [multipartout[i][0][1] for i in xrange(len(multipartout))]

    matplotlib.rcParams.update({'font.size': 31})
    plt.figure(0)

    ax1 = plt.subplot2grid((1,1), (0,0))
    ax1.plot(xo,xpo,'ro', zorder=1)
    ax1.set_xlim(-0.004, 0.004)
    ax1.set_ylim(-0.004, 0.004)
    plt.title('Values after lattice in x')
    plt.xlabel('x [m]')
    plt.ylabel('x\' []')

    plt.show()
项目:Differential-Algebra-Tracker    作者:OscarES    | 项目源码 | 文件源码
def plot_z_before_and_after(multipartin, multipartout):

    zin = [multipartin[i][0][4] for i in xrange(len(multipartin))]
    zpin = [multipartin[i][0][5] for i in xrange(len(multipartin))]

    zo = [multipartout[i][0][4] for i in xrange(len(multipartout))]
    zpo = [multipartout[i][0][5] for i in xrange(len(multipartout))]

    matplotlib.rcParams.update({'font.size': 31})
    plt.figure(0)

    ax1 = plt.subplot2grid((1,2), (0,0))
    ax1.plot(zin,zpin,'ro', zorder=1)
    plt.title('Initial values in z')
    plt.xlabel('z [m]')
    plt.ylabel('$\delta$ []')

    ax2 = plt.subplot2grid((1,2), (0,1))
    ax2.plot(zo,zpo,'ro', zorder=1)
    plt.title('Values after lattice in z')
    plt.xlabel('z [m]')
    plt.ylabel('$\delta$ []')

    plt.show()
项目:Differential-Algebra-Tracker    作者:OscarES    | 项目源码 | 文件源码
def plotEnvelope(envx,envy):
    plt.figure(0)
    ax4 = plt.subplot2grid((2,3), (0, 0), colspan=3)
    plt.plot(envx[:,0],envx[:,1],'ro')
    plt.title('Envelope in x by z')
    plt.xlabel('z [m]')
    plt.ylabel('Envelope in x [m]')
    ax5 = plt.subplot2grid((2,3), (1, 0), colspan=3)
    plt.plot(envy[:,0],envy[:,1],'bo')
    plt.title('Envelope in y by z')
    plt.xlabel('z [m]')
    plt.ylabel('Envelope in y [m]')

    plt.show()

## Plot def
项目:Primate_Visual_System    作者:pablomc88    | 项目源码 | 文件源码
def membranePotentials(start_time,time_step,sim_time,recorders,recorded_models,labels,
selected_cell,rows,cols,starting_row,starting_col,visual_stage,
path = '../../data/'):

    j = 0
    current_row = starting_row
    current_col = starting_col

    for population, model in recorded_models:

        if(isinstance(selected_cell, list) == False):
            [data,selected_senders,pop] = getData(population,model,recorders,[selected_cell])
        else:
            [data,selected_senders,pop] = getData(population,model,recorders,[selected_cell[j]])

        if(current_row<rows and current_col<cols):
            Vax = plt.subplot2grid((rows,cols), (current_row,current_col))
            V_m = (data[0]['V_m'])[selected_senders[0]] # membrane potential
            V_m = V_m[int(start_time/time_step):len(V_m)]
            time = np.arange(start_time,sim_time+time_step,time_step)

            Vax.plot( time[0:len(V_m)],V_m )
            Vax.set_title(labels[j])

        # save data
        np.savetxt(path+visual_stage+'/data/'+labels[j], V_m)
        if j==0:
            np.savetxt(path+visual_stage+'/data/time', time[0:len(V_m)])

        if(current_col<cols-1):
            current_col+=1
        else:
            current_col = 0
            current_row+=1

        j+=1

    Vax.set_xlabel('time (ms)')

# Plot PSTHs
项目:bark    作者:kylerbrown    | 项目源码 | 文件源码
def main(datfile, labelfile, outfile=None, shortcutfile=None, use_ops=True):
    if not labelfile:
        labelfile = os.path.splitext(datfile)[0] + '.csv'
    kill_shortcuts(plt)
    sampled = bark.read_sampled(datfile)
    assert len(sampled.attrs['columns']) == 1
    labels = bark.read_events(labelfile)
    labeldata = to_seconds(labels).data.to_dict('records')
    if len(labeldata) == 0:
        print('{} has no data'.format(labelfile))
        return
    shortcuts = build_shortcut_map(shortcutfile)
    opsfile = labelfile + '.ops.json'
    opstack = load_opstack(opsfile, labelfile, labeldata, use_ops)
    if not outfile:
        outfile = os.path.splitext(labelfile)[0] + '_edit.csv'
    plt.figure()
    # Oscillogram and Spectrogram get
    # three times the vertical space as the minimap.
    osc_ax = plt.subplot2grid((7, 1), (0, 0), rowspan=3)
    spec_ax = plt.subplot2grid((7, 1), (3, 0), rowspan=3, sharex=osc_ax)
    map_ax = plt.subplot2grid((7, 1), (6, 0))
    # Segement review is a context manager to ensure a save prompt
    # on exit. see SegmentReviewer.__exit__
    with SegmentReviewer(osc_ax, spec_ax, map_ax, sampled, opstack, shortcuts,
                         outfile, labels.attrs, opsfile) as reviewer:
        reviewer.connect()
        plt.show(block=True)
项目:NTM-Keras    作者:SigmaQuan    | 项目源码 | 文件源码
def update(self, matrix_list, name_list):
        # draw first line
        axes_input = plt.subplot2grid((3, 1), (0, 0), colspan=1)
        axes_input.set_aspect('equal')
        plt.imshow(matrix_list[0], interpolation='none')
        axes_input.set_xticks([])
        axes_input.set_yticks([])

        # draw second line
        axes_output = plt.subplot2grid((3, 1), (1, 0), colspan=1)
        plt.imshow(matrix_list[1], interpolation='none')
        axes_output.set_xticks([])
        axes_output.set_yticks([])

        # draw third line
        axes_predict = plt.subplot2grid((3, 1), (2, 0), colspan=1)
        plt.imshow(matrix_list[2], interpolation='none')
        axes_predict.set_xticks([])
        axes_predict.set_yticks([])

        # # add text
        # plt.text(-2, -19.5, name_list[0], ha='right')
        # plt.text(-2, -7.5, name_list[1], ha='right')
        # plt.text(-2, 4.5, name_list[2], ha='right')
        # plt.text(6, 10, 'Time $\longrightarrow$', ha='right')

        # set tick labels invisible
        make_tick_labels_invisible(plt.gcf())
        # adjust spaces
        plt.subplots_adjust(hspace=0.05, wspace=0.05, bottom=0.1, right=0.8, top=0.9)
        # add color bars
        # *rect* = [left, bottom, width, height]
        cax = plt.axes([0.85, 0.125, 0.015, 0.75])
        plt.colorbar(cax=cax)

        # show figure
        # plt.show()
        plt.draw()
        plt.pause(0.025)
        # plt.pause(15)
项目:xdesign    作者:tomography    | 项目源码 | 文件源码
def _pyramid(N):
    """Generates the corner positions, grid size, and column/row spans for
    a pyramid image.

    Parameters
    --------------
    N : int
        the total number of images in the pyramid.

    Returns
    -------------
    params : list of lists
        Contains the params for subplot2grid for each of the N images in the
        pyramid. [W,corner,span] W is the total grid size, corner is the
        location of a particular axies, and span is the size of a paricular
        axies.
    """
    num_levels = round(N / float(3))  # the number of levels in the pyramid
    W = int(2**num_levels)  # grid size of the pyramid

    params = [p % 3 for p in range(0, N)]
    lcorner = [0, 0]  # the min corner of this level
    for n in range(0, N):
        level = int(n / 3)  # pyramid level
        span = int(W / (2**(level + 1)))  # span in num of grid spaces
        corner = list(lcorner)  # the min corner of this tile

        if params[n] == 0:
            lcorner[0] += span
            lcorner[1] += span
        elif params[n] == 2:
            corner[0] = lcorner[0] - span
        elif params[n] == 1:
            corner[1] = lcorner[1] - span

        params[n] = [W, corner, span]
        # print(params[n])

    return params
项目:aiida-quantumespresso    作者:aiidateam    | 项目源码 | 文件源码
def plot_dynamics_data(self, start=0):

        import matplotlib.pyplot as plt

        ax1 = plt.subplot2grid((2,2), (0,0), colspan=2)
        ax2 = plt.subplot2grid((2,2), (1,0))
        ax3 = plt.subplot2grid((2,2), (1,1))

        self.df[start:len(self.df)][["etot", "econt", "econs"]].plot(ax=ax1)
        ((self.df[start:len(self.df)].etot-self.df[start:len(self.df)].econs)/(self.df[start:len(self.df)].econs-self.df[start:len(self.df)].econt)).plot(ax=ax2)
        self.df.tempp[start:len(self.df)].plot(ax3)
        plt.show()
项目:aiida-quantumespresso    作者:aiidateam    | 项目源码 | 文件源码
def plot_temp_data(self, start=0):

        import matplotlib.pyplot as plt
        import ase.data

        ax1 = plt.subplot2grid((2,2), (0,0), colspan=2)
        ax2 = plt.subplot2grid((2,2), (1,0))
        ax3 = plt.subplot2grid((2,2), (1,1))

        ekins = []
        et    = []

        for i in range(len(self.ordering)):
            at_num   = self.struct.get_ase().get_atomic_numbers()[self.ordering[i][0]]
            w_name   = ase.data.chemical_symbols[at_num]

            for at in range(len(self.ordering[i])):
                ion_key        = w_name+"_"+str(self.ordering[i][at])

                if "ekin_"+ion_key not in self.df:
                    print "Generating"
                    self.generate_species_data()

                ekins.append("ekin_"+ion_key)
                et.append("temp_"+ion_key)

        self.df[et].plot(ax=ax1, legend=False)
        self.df[et].mean().plot(kind='bar', ax=ax2, yerr=self.df[et].std())
        self.df.all_temp.plot(ax=ax3)
        self.df.tempp.plot(ax=ax3)

        plt.show()
项目:aiida-quantumespresso    作者:aiidateam    | 项目源码 | 文件源码
def plot_temp_data_by_species(self, start=0):

        import matplotlib.pyplot as plt
        import ase.data

        specs = len(self.ordering)

        axes = []
        axes_2 = []
        for i in range(specs):
            axes.append(plt.subplot2grid((specs,2), (i,0)))
            axes_2.append(plt.subplot2grid((specs,2), (i,1)))

        for i in range(len(self.ordering)):

            et    = []

            at_num   = self.struct.get_ase().get_atomic_numbers()[self.ordering[i][0]]
            w_name   = ase.data.chemical_symbols[at_num]

            for at in range(len(self.ordering[i])):
                ion_key        = w_name+"_"+str(self.ordering[i][at])
                et.append("temp_"+ion_key)


            self.df[et].plot(ax=axes[i], legend=False)
            (self.df[et].sum(axis=1)/len(self.ordering[i])).plot(ax=axes_2[i], legend=False)

        plt.show()
项目:Python-Image-Processing    作者:amirfrsd    | 项目源码 | 文件源码
def recognitionFunc(filePath):
    recognized=[]
    exampleNumberColors=open('numtext.txt','r').read()
    exampleNumberColors=exampleNumberColors.split('\n')
    i=Image.open(filePath)
    iArray=np.array(i)
    iArrayList=iArray.tolist()
    inquestion=str(iArrayList)
    for examples in exampleNumberColors:
        if(len(examples)>3):
            splitTexts=examples.split('::')
            numberIs=splitTexts[0]
            pixelArrayIs=splitTexts[1]
            eachPixelEx=pixelArrayIs.split('],')
            eachPixelInq=inquestion.split('],')
            a=0
            while(a<len(eachPixelEx)):
                if(eachPixelEx[a]==eachPixelInq[a]):
                    recognized.append(int(numberIs))
                a += 1
    c=Counter(recognized)
    print(c)
    print(max(c.values()))
    xAxis=[]
    yAxis=[]
    for eachNumber in c:
        xAxis.append(eachNumber)
        yAxis.append(c[eachNumber])
    ax1=plot.subplot2grid((4,4),(0,0),rowspan=1,colspan=4)
    ax2=plot.subplot2grid((4,4),(1,0),rowspan=3,colspan=4)
    ax1.imshow(iArray)
    print(xAxis,yAxis)
    ax2.bar(xAxis,yAxis,align="center")
    plot.ylim(350)
    plot.show()
项目:quantdigger    作者:andyzsf    | 项目源码 | 文件源码
def add_subplot(self, *args):
        num_axes = sum(args)
        for i, ratio in enumerate(args):
            if i > 0:
                plt.subplot2grid((num_axes, 1), (sum(args[:i]), 0),
                                 rowspan = ratio, sharex = self.fig.axes[0])
            else:
                plt.subplot2grid((num_axes, 1), (sum(args[:i]), 0), rowspan = ratio)

        #self.slider = mwidgets.Slider(xslider, "slider", '', 0, len(price_data), len(price_data), len(price_data)/100, "%d")
        ##kwindow.on_changed(observer_slider)
        ##observer_slider.on_changed(kwindow)
        #signal = SignalWindow(axk, zip(zip(entry_x,entry_y),zip(exit_x,exit_y)), colors, slw)
项目:LIE    作者:EmbraceLife    | 项目源码 | 文件源码
def animate(i):
    # dirpath is a global variable from above
    dirpath = "/Users/Natsume/Downloads/temp_folders/demo_cifar/cifar_plot_weights"

    # # make an ordered list of layers to plot
    # layer_order = [['images'], ['convolution_0'], ['conv_layer1'], ['convolution_1'], ['conv_layer2']]

    # define how many rows of subplots we need
    num_cols = len(layer_order)

    # i from animation(), start from 0, repetition

    # empty file name
    img_file = None

    # plt.figure(figsize=(5, 10))
    # plot layer one by one
    for col in range(num_cols):

        # access all filenames in the dirpath
        for dirpath, _, filenames in os.walk(dirpath):
            # looping through every filename
            for filename in filenames:

                # search all filenames with a row's keywords
                # "epoch"+str(i+1): make sure all layers in one figure share the same epoch
                if filename.find(layer_order[col]) > -1 and filename.find(str(i+1)+".png")> -1:
                    img_file = dirpath + '/' + filename
                    img=mpimg.imread(img_file)

                    ax = plt.subplot2grid((3, num_cols), (0, col), rowspan=3, colspan=1)
                    ax.set_title(layer_order[col] + "_epoch_" + str(i+1))
                    ax.imshow(img)
    # plt.show() can plot all subplots, meaning all subplots are stored inside plt
    return plt
项目:py-NnK    作者:FMassin    | 项目源码 | 文件源码
def demo(self):

        # Axes Plots
        fig = plt.figure(figsize=plt.figaspect(1.))
        p = ((0,0), (1,0), (0,1), (1,1))
        cb=[0,0,0,1]
        for i,v in enumerate(self.simple_models.keys()):
            ax = plt.subplot2grid((2,2), p[i], projection='3d', aspect='equal', ylim=[-1,1], xlim=[-1,1], zlim=[-1,1])
            example = SeismicSource(self.simple_models[v]['definition'])
            example.Aki_Richards.plot(wave='P', style='*', ax=ax, cbarxlabel='P-wave amplitudes', cb=cb[i])
            ax.set_title(self.simple_models[v]['name'])

        plt.tight_layout()
项目:py-NnK    作者:FMassin    | 项目源码 | 文件源码
def demodc(self):

        # Axes Plots
        fig = plt.figure(figsize=plt.figaspect(2.))
        p = ((0,0), (1,0), (2,0))
        cb=[0,0,1]
        for i,v in enumerate(self.simple_models_dc.keys()):
            ax = plt.subplot2grid((3,1), p[i], projection='3d', aspect='equal', ylim=[-1,1], xlim=[-1,1], zlim=[-1,1])
            example = SeismicSource(self.simple_models_dc[v]['definition'])
            example.Aki_Richards.plot(wave='P', style='*', ax=ax, cbarxlabel='P-wave amplitudes', cb=cb[i])
            ax.set_title(self.simple_models_dc[v]['name'])

        plt.tight_layout()
项目:ML-Forex-Forecasting    作者:jul1278    | 项目源码 | 文件源码
def plot_tick_range(tick_path, range_start, range_end):

    if os.path.exists(tick_path) == False:
        print(tick_path + ' file doesnt exist')

        quit()

    date_cols = ['RateDateTime']

    df = pd.read_csv(tick_path, usecols=['RateDateTime','RateBid','RateAsk'])

    start_index = tfh.find_index_closest_date(range_start, tick_path)
    end_index = tfh.find_index_closest_date(range_end, tick_path)

    # dont proceed if we didnt find indices
    if (start_index is None or end_index is None):
        print('start_index or end_index was None')
        quit()

    ticks_s = df.iloc[start_index:end_index]

    ticks = (ticks_s['RateAsk'] + ticks_s['RateBid']) / 2.0

    dates_dt = [dt.datetime.strptime(str.split(x, '.')[0], '%Y-%m-%d %H:%M:%S') for x in ticks_s['RateDateTime'].values]

    dates = mdates.date2num(dates_dt)

    #fig = plt.figure()
    #ax1 = plt.subplot2grid((1,1), (0,0))

    plt.plot_date(dates, ticks, 'b-')
项目:challenges    作者:py-study-group    | 项目源码 | 文件源码
def plotting():  # plots the various crime rates
    fig = plt.figure()
    ax1 = plt.subplot2grid((1, 1), (0, 0))
    perc_change.plot(ax=ax1, linewidth=3)
    total_crime_perc_change.plot(ax=ax1, linewidth=10, color='black', label='mean crime rate')

    ax1.legend(loc="lower left")
    plt.title("Percentage change in crime rates compared to starting year")
    plt.show()
项目:odin    作者:imito    | 项目源码 | 文件源码
def subplot2grid(shape, loc, colspan=1, rowspan=1):
  from matplotlib import pyplot as plt
  return plt.subplot2grid(shape, loc, colspan=colspan, rowspan=rowspan)
项目:Food-Classification    作者:Tkd-Alex    | 项目源码 | 文件源码
def nearestimage_and_representation(paths_training, index_training, X_training, y_training, paths_test, index_test, X_test, y_test, distance, accuracy, matrix):
    plt.figure()

    query_image = sio.imread(paths_test[index_test])
    plt.subplot2grid((2,3), (0, 0))
    if(y_test[index_test] == 0):
        typeofclass = "Food"
    else:
        typeofclass = "Not-Food"
    plt.title("Query image {0}".format(paths_test[index_test]) )
    plt.imshow(query_image)

    plt.subplot2grid((2,3), (0, 1))
    plt.title("Class {0}".format(typeofclass) )
    plt.plot(X_test[index_test])

    closest_im = sio.imread(paths_training[index_training])
    plt.subplot2grid((2,3), (1, 0))
    if(y_training[index_training] == 0):
        typeofclass = "Food"
    else:
        typeofclass = "Not-Food"
    plt.title("Closest Im {0}".format(paths_training[index_training]) )
    plt.imshow(closest_im)

    plt.subplot2grid((2,3), (1, 1))
    plt.title("Class {0}".format(typeofclass) )
    plt.plot(X_training[index_training])

    plt.subplot2grid((2,3), (0, 2), rowspan=2)
    plt.title("Distance {0} - Accuracy {1}%\nConfusion Matrix\n {2}".format(distance, accuracy, matrix))
    plt.plot(X_test[index_test], color='red')
    plt.plot(X_training[index_training], color='blue')

    plt.show()
项目:wavelet-denoising    作者:mackaiver    | 项目源码 | 文件源码
def __init__(self, left_cube, right_cube, trans_factor, cmap='viridis'):
        self.fig = plt.figure()

        ax1 = plt.subplot2grid((2, 2), (0, 0))
        ax2 = plt.subplot2grid((2, 2), (0, 1))
        ax3 = plt.subplot2grid((2, 2), (1, 0), colspan=2)

        ax1.tick_params(labelbottom='off', labelleft='off')
        ax2.tick_params(labelbottom='off', labelleft='off')

        ax3.set_xlabel('Time Step in a.u.')
        ax3.set_ylabel('Trigger Criterion in a.u.')

        vmax = left_cube.max()
        self.l_quad = ax1.pcolormesh(left_cube[0], cmap=cmap, vmin=0, vmax=vmax)
        self.r_quad = ax2.pcolormesh(left_cube[0], cmap=cmap, vmin=0, vmax=vmax)

        self.line,  = ax3.plot(0, trans_factor[0])

        ax3.set_xlim([0, len(trans_factor)])
        ax3.set_ylim([0, trans_factor.max() + 1])

        self.left_cube = left_cube
        self.right_cube = right_cube
        self.trans_factor = trans_factor
        self.x = []
        self.y = []
项目:neural-networks-and-deep-learning    作者:skylook    | 项目源码 | 文件源码
def plot_errors(error_locations, erroneous_predictions=None):
    test_x, test_y = test_data[0].eval(), test_data[1].eval()
    fig = plt.figure()
    error_images = [np.array(test_x[i]).reshape(28, -1) for i in error_locations]
    n = min(40, len(error_locations))
    for j in range(n):
        ax = plt.subplot2grid((5, 8), (j/8, j % 8))
        ax.matshow(error_images[j], cmap = matplotlib.cm.binary)
        ax.text(24, 5, test_y[error_locations[j]])
        if erroneous_predictions:
            ax.text(24, 24, erroneous_predictions[j])
        plt.xticks(np.array([]))
        plt.yticks(np.array([]))
    plt.tight_layout()
    return plt
项目:SOAR    作者:araujolma    | 项目源码 | 文件源码
def plotResultsAed(self):

        tt = self.traj.tt
        tp = self.traj.tp
        # Aed plots
        LL,  DD,  CCL,  CCD,  QQ = self.__calcAedTab(self.traj.tt,
                                                     self.traj.xx, self.uu)
        Lp,  Dp,  CLp,  CDp,  Qp = self.__calcAedTab(self.traj.tp,
                                                     self.traj.xp, self.up)

        plt.subplot2grid((6, 2), (0, 0), rowspan=2, colspan=2)
        plt.plot(tt, LL, '.-b', tp, Lp, '.r', tt, DD, '.-g', tp, Dp, '.r')
        plt.grid(True)
        plt.ylabel("L and D [kN]")

        plt.subplot2grid((6, 2), (2, 0), rowspan=2, colspan=2)
        plt.plot(tt, CCL, '.-b', tp, CLp, '.r', tt, CCD, '.-g', tp, CDp, '.r')
        plt.grid(True)
        plt.ylabel("CL and CD [-]")

        plt.subplot2grid((6, 2), (4, 0), rowspan=2, colspan=2)
        plt.plot(tt, QQ, '.-b', tp, Qp, '.r')
        plt.grid(True)
        plt.ylabel("qdin [kPa]")

        plt.show()

        return None
项目:SOAR    作者:araujolma    | 项目源码 | 文件源码
def plotSol(sizes,t,x,u,pi,constants,restrictions,opt=dict()):

    plt.subplot2grid((8,4),(0,0),colspan=5)
    plt.plot(t,x[:,0]*180/numpy.pi,)
    plt.grid(True)
    plt.ylabel("theta (deg)")
    if opt.get('mode','sol') == 'sol':
        I = calcI(sizes,x,u,pi,constants,restrictions)
        titlStr = "Current solution: I = {:.4E}".format(I)
        if opt.get('dispP',False):
            P = opt['P']
            titlStr = titlStr + " P = {:.4E} ".format(P)
        if opt.get('dispQ',False):
            Q = opt['Q']
            titlStr = titlStr + " Q = {:.4E} ".format(Q)
    elif opt['mode'] == 'var':
        titlStr = "Proposed variations"
    else:
        titlStr = opt['mode']
    #
    plt.title(titlStr)
    plt.subplot2grid((8,4),(1,0),colspan=5)
    plt.plot(t,x[:,1]*180/numpy.pi,'g')
    plt.grid(True)
    plt.ylabel("omega (deg/s)")
    plt.subplot2grid((8,4),(2,0),colspan=5)
    plt.plot(t,u[:,0],'k')
    plt.grid(True)
    plt.ylabel("u1 [-]")
    plt.subplot2grid((8,4),(3,0),colspan=5)
    plt.plot(t,numpy.tanh(u[:,0]),'r')
    plt.grid(True)
    plt.ylabel("contr [-]")

    plt.subplots_adjust(0.0125,0.0,0.9,2.5,0.2,0.2)
    plt.show()
    print("pi =",pi,"\n")
#
项目:SOAR    作者:araujolma    | 项目源码 | 文件源码
def plotSol(sizes,t,x,u,pi,constants,restrictions,opt=dict()):

    plt.subplot2grid((8,4),(0,0),colspan=5)
    plt.plot(t,x[:,0],)
    plt.grid(True)
    plt.ylabel("x")
    if opt.get('mode','sol') == 'sol':
        I = calcI(sizes,x,u,pi,constants,restrictions)
        titlStr = "Current solution: I = {:.4E}".format(I)
        if opt.get('dispP',False):
            P = opt['P']
            titlStr = titlStr + " P = {:.4E} ".format(P)
        if opt.get('dispQ',False):
            Q = opt['Q']
            titlStr = titlStr + " Q = {:.4E} ".format(Q)
    elif opt['mode'] == 'var':
        titlStr = "Proposed variations"
    else:
        titlStr = opt['mode']
    #
    plt.title(titlStr)
    plt.subplot2grid((8,4),(1,0),colspan=5)
    plt.plot(t,x[:,1],'g')
    plt.grid(True)
    plt.ylabel("y")
    plt.subplot2grid((8,4),(2,0),colspan=5)
    plt.plot(t,u[:,0],'k')
    plt.grid(True)
    plt.ylabel("u1 [-]")
    plt.subplot2grid((8,4),(3,0),colspan=5)
    plt.plot(t,numpy.tanh(u[:,0]),'r')
    plt.grid(True)
    plt.ylabel("contr [-]")

    plt.subplots_adjust(0.0125,0.0,0.9,2.5,0.2,0.2)
    plt.show()
    print("pi =",pi,"\n")
#
项目:decoding_challenge_cortana_2016_3rd    作者:kingjr    | 项目源码 | 文件源码
def _onclick_help(event, params):
    """Function for drawing help window"""
    import matplotlib.pyplot as plt
    text, text2 = _get_help_text(params)

    width = 6
    height = 5

    fig_help = figure_nobar(figsize=(width, height), dpi=80)
    fig_help.canvas.set_window_title('Help')
    ax = plt.subplot2grid((8, 5), (0, 0), colspan=5)
    ax.set_title('Keyboard shortcuts')
    plt.axis('off')
    ax1 = plt.subplot2grid((8, 5), (1, 0), rowspan=7, colspan=2)
    ax1.set_yticklabels(list())
    plt.text(0.99, 1, text, fontname='STIXGeneral', va='top', weight='bold',
             ha='right')
    plt.axis('off')

    ax2 = plt.subplot2grid((8, 5), (1, 2), rowspan=7, colspan=3)
    ax2.set_yticklabels(list())
    plt.text(0, 1, text2, fontname='STIXGeneral', va='top')
    plt.axis('off')

    tight_layout(fig=fig_help)
    # this should work for non-test cases
    try:
        fig_help.canvas.draw()
        fig_help.show(warn=False)
    except Exception:
        pass
项目:Optics    作者:danustc    | 项目源码 | 文件源码
def pupil_showcross(pf):
    # display the pupil function from top and cross section.
    NY, NX = pf.shape
    ry = int(NY/2.)
    rx = int(NX/2.)
    yy = (np.arange(NY)-ry)/ry
    xx = (np.arange(NX)-rx)/rx
    [MX, MY] = np.meshgrid(xx,yy)
    figp = plt.figure(figsize = (7.9,3.2))
    grid_size = (1,5)
    plt.subplot2grid(grid_size,(0,0), rowspan = 1, colspan = 2)
    plt.subplot2grid(grid_size,(0,2), rowspan = 1, colspan = 3)
    ax1, ax2 = figp.axes
    ax1.pcolor(MX,MY,pf,cmap = 'RdYlBu_r')
    ax1.get_xaxis().set_visible(False)
    ax1.get_yaxis().set_visible(False)

    ax2.plot(xx,pf[ry, :], '-r', linewidth = 2, label = 'kx')
    ax2.plot(yy,pf[:,rx], '-g', linewidth = 2, label = 'ky')
    ax2.set_xlabel('k', fontsize = 14)
    ax2.set_ylabel('Wavelength', fontsize = 14)
    ax2.set_ylim([-1,1])
    ax2.legend(['x', 'y'], fontsize=12)
    ax2.set_xticks([-1,-0.5,0,0.5,1] )

    plt.tight_layout()
    return figp
项目:Optics    作者:danustc    | 项目源码 | 文件源码
def pupil_showcross(pf):
    # display the pupil function from top and cross section.
    NY, NX = pf.shape
    ry = int(NY/2.)
    rx = int(NX/2.)
    yy = (np.arange(NY)-ry)/ry
    xx = (np.arange(NX)-rx)/rx
    [MX, MY] = np.meshgrid(xx,yy)
    figp = plt.figure(figsize = (7.9,3.2))
    grid_size = (1,5)
    plt.subplot2grid(grid_size,(0,0), rowspan = 1, colspan = 2)
    plt.subplot2grid(grid_size,(0,2), rowspan = 1, colspan = 3)
    ax1, ax2 = figp.axes
    ax1.pcolor(MX,MY,pf,cmap = 'RdYlBu_r')
    ax1.get_xaxis().set_visible(False)
    ax1.get_yaxis().set_visible(False)

    ax2.plot(xx,pf[ry, :], '-r', linewidth = 2, label = 'kx')
    ax2.plot(yy,pf[:,rx], '-g', linewidth = 2, label = 'ky')
    ax2.set_xlabel('k', fontsize = 14)
    ax2.set_ylabel('Wavelength', fontsize = 14)
    ax2.set_ylim([-1,1])
    ax2.legend(['x', 'y'], fontsize=12)
    ax2.set_xticks([-1,-0.5,0,0.5,1] )

    plt.tight_layout()
    return figp
项目:TensorFlow_DCIGN    作者:yselivonchyk    | 项目源码 | 文件源码
def _show_image(img, original=True):
  # index = 322 if original else 326
  index = (0, 1) if original else (4, 1)
  # ax = plt.subplot(index)
  ax = plt.subplot2grid((7, 2), index, rowspan=3)
  ax.imshow(img)
  ax.set_title('Original' if original else 'Reconstruction')
  ax.axis('off')
项目:TensorFlow_DCIGN    作者:yselivonchyk    | 项目源码 | 文件源码
def animate(cur, enc, img, reco):
  fig = vis.get_figure()

  original = data_to_img(img[cur])
  reconstr = data_to_img(reco[cur])

  _show_image(original)
  _show_image(reconstr, original=False)

  # animation
  ax = plt.subplot2grid((7, 2), (0, 0), rowspan=7, projection='3d')
  ax.set_title('Trajectory')
  ax.axes.get_xaxis().set_ticks([])
  ax.axes.get_yaxis().set_ticks([])
  ax.set_zticks([])

  if enc.shape[1] > 3:
    enc = enc[:, :4]

  # white
  data = enc[cur:]
  ax.scatter(data[:, 0], data[:, 1], data[:, 2], c='w', s=1, zorder=15)
  # old
  tail_len = max(0, cur - TAIL_LENGTH)
  # print(tail_len)
  if tail_len > 0:
    data = enc[:tail_len]
    ax.scatter(data[:, 0], data[:, 1], data[:, 2], c='black', zorder=10, s=1,)
  # recent
  for i in range(0, -TAIL_LENGTH, -1):
    j = i + cur
    if j >= 0:
      # print(cur, i)
      data = enc[j]
      ax.scatter(data[0], data[1], data[2], c='b', s=(i+TAIL_LENGTH)/5, zorder=5)

  plt.show()
项目:pyefd    作者:hbldh    | 项目源码 | 文件源码
def plot_efd(coeffs, locus=(0., 0.), image=None, contour=None, n=300):
    """Plot a ``[2 x (N / 2)]`` grid of successive truncations of the series.

    .. note::

        Requires `matplotlib <http://matplotlib.org/>`_!

    :param numpy.ndarray coeffs: ``[N x 4]`` Fourier coefficient array.
    :param list, tuple or numpy.ndarray locus:
        The :math:`A_0` and :math:`C_0` elliptic locus in [#a]_ and [#b]_.
    :param int n: Number of points to use for plotting of Fourier series.

    """
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        print("Cannot plot: matplotlib was not installed.")
        return

    N = coeffs.shape[0]
    N_half = int(np.ceil(N / 2))
    n_rows = 2

    t = np.linspace(0, 1.0, n)
    xt = np.ones((n,)) * locus[0]
    yt = np.ones((n,)) * locus[1]

    for n in _range(coeffs.shape[0]):
        xt += (coeffs[n, 0] * np.cos(2 * (n + 1) * np.pi * t)) + \
              (coeffs[n, 1] * np.sin(2 * (n + 1) * np.pi * t))
        yt += (coeffs[n, 2] * np.cos(2 * (n + 1) * np.pi * t)) + \
              (coeffs[n, 3] * np.sin(2 * (n + 1) * np.pi * t))
        ax = plt.subplot2grid((n_rows, N_half), (n // N_half, n % N_half))
        ax.set_title(str(n + 1))
        if contour is not None:
            ax.plot(contour[:, 1], contour[:, 0], 'c--', linewidth=2)
        ax.plot(yt, xt, 'r', linewidth=2)
        if image is not None:
            ax.imshow(image, plt.cm.gray)

    plt.show()
项目:Buffe    作者:bentzinir    | 项目源码 | 文件源码
def _init_display(self):
        self.reset()
        self.t = 0
        if self.vis_flag:
            self.fig = plt.figure()
            self.ax = plt.subplot2grid((2, 2), (0, 0), colspan=2, rowspan=2)
            self.x_expert = self.reference_contour()[:, 2:]
            self.scat_agent = self.ax.scatter(self.state[2], self.state[3], s=180, marker='o', color='r')
            self.scat_expert = self.ax.scatter(self.x_expert[0][0], self.x_expert[0][1], s=180, marker='o', color='b')
项目:Buffe    作者:bentzinir    | 项目源码 | 文件源码
def __init__(self, run_dir):

        r = 10.
        game_params = {
            'r': r,
            'dt': 1./9,
            'host_speed': 10/3.6,
            'target_speed': 5.,
            'num_of_targets': 5,
        }

        self._connect(game_params)

        self._train_params()

        self.fig = plt.figure()
        self.ax = plt.subplot2grid((2, 2), (0, 0), colspan=2, rowspan=2)

        self.run_dir = run_dir

        subprocess.Popen(self.run_dir + "./simulator")

        self.pipe_module = tf.load_op_library(self.run_dir + 'pipe.so')

        plt.ion()
        plt.show()
项目:Buffe    作者:bentzinir    | 项目源码 | 文件源码
def init_theano_funcs(self):

        self.test_model = t.function(
            inputs=[self.v_h_0, self.x_h_0, self.v_t_0, self.x_t_0, self.a_t_0, self.is_aggressive, self.n_steps_],
            outputs=[self.model.v_h, self.model.x_h, self.model.v_t, self.model.x_t, self.model.grad_mean, self.model.params_abs_norm],
            givens={},
            name='test_model_func',
            on_unused_input='ignore',
        )

        self.train_model = t.function(
            inputs=[self.v_h_0, self.x_h_0, self.v_t_0, self.x_t_0, self.a_t_0, self.is_aggressive, self.lr_, self.n_steps_],
            outputs=[self.model.cost_a, self.model.cost_t],
            updates=self.model.updates,
            givens={},
            name='train_func',
            on_unused_input='ignore',
        )

        self.avg_cost_a = 999
        self.avg_cost_t = 999
        self.grad_mean = 0
        self.param_abs_norm = 0

        self.fig = plt.figure()
        self.ax = plt.subplot2grid((2,2), (0,0), colspan=2, rowspan=2)

        plt.ion()
        plt.show()
        plt.axis('equal')
项目:Buffe    作者:bentzinir    | 项目源码 | 文件源码
def __init__(self):

        r = 1.
        game_params = {
            'r': r,
            'dt': 0.15,
            'v_0': 0.2,
            'num_of_targets': 5,
            'dist_in_seconds': 3.,
            'alpha_accel': 0.5,
            'alpha_progress': 0.5,
            'alpha_accident': 0.5,
            'p_aggressive': 0.5,
            'x_goal': 0.5 * r * np.pi,
            'require_distance': 0.25 * r * np.pi,
            'host_length': 0.125 * r * np.pi,
            'gamma': 0.95,
        }

        self._connect(game_params)

        self.fig = plt.figure()
        self.ax = plt.subplot2grid((2, 2), (0, 0), colspan=2, rowspan=2)

        plt.ion()
        plt.show()
项目:acl2017-interactive_summarizer    作者:UKPLab    | 项目源码 | 文件源码
def plot_aggregate(labels, accepts_rejects, rejects, ub_score, sys_score, soa, break_iteration, filename):
    colors = ['g','b','r', '#8E4585']
    linestyles = ['->', '-o', '-', '-x']

    f, axis = plt.subplots(2, sharex=True, sharey=False, figsize=(4, 6))
    axis[0] = plt.subplot2grid((8, 12), (0, 0), rowspan=5, colspan=12)
    axis[1] = plt.subplot2grid((8, 12), (5, 0), rowspan=3, colspan=12)

    axis[0].plot(range(len(accepts_rejects[0][0:break_iteration])), len(accepts_rejects[0][0:break_iteration]) * [ub_score[0][0]], 'k--', label = 'Upper bound', linewidth=2)

    common_score = []
    for i in range(len(labels)):
        common_score.append(sys_score[i][0])

    initial_score = max(set(common_score), key=common_score.count)

    for i in range(len(labels)):
        sys_score[i][0] = initial_score

    for i in range(len(labels)):
        y = sys_score[i][0:break_iteration]
        axis[0].plot(range(len(y)), y, linestyles[i], color=colors[i], label='%s' % labels[i], linewidth=1.5)

    axis[0].set_ylabel('ROUGE 2', fontsize=15)
    axis[0].legend(loc="best", fontsize=12)
    axis[0].set_xticks(np.arange(0, break_iteration, 1))
    axis[0].set_autoscale_on(True)
    axis[0].grid(True)
    f.subplots_adjust(hspace=0.1)

    for i in range(len(labels)):
        y = accepts_rejects[i][1:break_iteration+1]
        axis[1].plot(range(len(y)), y, linestyles[i], color=colors[i], label='%s' % labels[i], linewidth=1.5)

    axis[1].grid(True)
    axis[1].set_xlabel("\# Iterations", fontsize=13)
    axis[1].set_ylabel('\# Feedbacks', fontsize=13)
    axis[1].set_xticks(np.arange(0, break_iteration, 1))
    axis[1].set_xticklabels(np.arange(0, break_iteration, 1))
    plt.tight_layout()
    savefig(filename)
项目:real-nvp    作者:taesung89    | 项目源码 | 文件源码
def save_images_with_nll(images, nlls):
  num_images = images.shape[0]
  num_images_per_row = 4
  num_images_per_column = (num_images + num_images_per_row - 1) // num_images_per_row
  idx = 0
  for i in range(num_images_per_column):
    for j in range(num_images_per_row):
      plt.subplot2grid((num_images_per_column,num_images_per_row),(i, j))
      plt.axis('off')
      plt.imshow(images[idx])
      plt.title('%f' % nlls[idx])      
      idx += 1
      if idx >= num_images:
        plt.savefig('test_results/samples_%s.png' % time.strftime("%m_%d_%H_%M_%S"), bbox_inches='tight')
        return
项目:extract    作者:dblalock    | 项目源码 | 文件源码
def plotSeqAndFeatures(seq, X, createFiltAx=False, padBothSides=False, capYLim=1000):
    """plots the time series above the associated feature matrix"""
    plt.figure(figsize=(10, 8))
    if createFiltAx:
        nRows = 4
        nCols = 7
        axSeq = plt.subplot2grid((nRows,nCols), (0,0), colspan=(nCols-1))
        axSim = plt.subplot2grid((nRows,nCols), (1,0), colspan=(nCols-1), rowspan=(nRows-1))
        axFilt = plt.subplot2grid((nRows,nCols), (1,nCols-1), rowspan=(nRows-1))
        axes = (axSeq, axSim, axFilt)
    else:
        nRows = 4
        nCols = 1
        axSeq = plt.subplot2grid((nRows,nCols), (0,0))
        axSim = plt.subplot2grid((nRows,nCols), (1,0), rowspan=(nRows-1))
        axes = (axSeq, axSim)

    for ax in axes:
        ax.autoscale(tight=True)

    axSeq.plot(seq)
    axSeq.set_ylim([seq.min(), min(capYLim, seq.max())])

    if padBothSides:
        padLen = (len(seq) - X.shape[1]) // 2
        Xpad = ar.addZeroCols(X, padLen, prepend=True)
        Xpad = ar.addZeroCols(Xpad, padLen, prepend=False)
    else:
        padLen = len(seq) - X.shape[1]
        Xpad = ar.addZeroCols(Xpad, padLen, prepend=False)
    axSim.imshow(Xpad, interpolation='nearest', aspect='auto')

    axSeq.set_title("Time Series")
    axSim.set_title("Feature Matrix")

    if createFiltAx:
        axFilt.set_title("Learned Filter")
        return axSeq, axSim, axFilt
    return axSeq, axSim
项目:extract    作者:dblalock    | 项目源码 | 文件源码
def makeFig1():
    ts = getFig1Ts()

    # set up axes
    ax1 = plt.subplot2grid((2,2), (0,0), colspan=2)
    ax2 = plt.subplot2grid((2,2), (1,0))
    ax3 = plt.subplot2grid((2,2), (1,1))
    axes = [ax1, ax2, ax3]

    for ax in axes:
        ax.autoscale(tight=True)
        sb.despine(left=True, ax=ax)

    ts.plot(showLabels=False, showBounds=False, ax=ax1)

    lengths = [150]
    ts_sota = labelTs_sota(ts, lengths)
    ts_sota.plot(showLabels=False, ax=ax2)

    ts_ff = labelTs_ff(ts, 100, 200) # Lmin, Lmax
    ts_ff.plot(showLabels=False, ax=ax3)

    plt.setp(ax3.get_yticklabels(), visible=False)
    ax1.set_title("Patterns in Dishwasher Dataset")
    ax1.set_xlabel("Minute")
    ax2.set_title("State-of-the-art")
    ax3.set_title("Proposed")

    plt.tight_layout()
    plt.show()
项目:coliform-project    作者:uprm-research-resto    | 项目源码 | 文件源码
def showPlot(rgb_array):
    """
    Shows rgb array plots for image
    :param rgb_array: rgb array to be analyzed
    """
    rgb_array_red = rgb_array * 1
    rgb_array_green = rgb_array * 1
    rgb_array_blue = rgb_array * 1
    rgb_array_hist = rgb_array

    f5 = plt.figure()
    f5.canvas.set_window_title('RGB Plots')

    lu1 = setImageColor(rgb_array_red, 'r')
    plt.subplot2grid((2, 3), (0, 0))
    plt.imshow(lu1)

    lu2 = setImageColor(rgb_array_green, 'g')
    plt.subplot2grid((2, 3), (0, 1))
    plt.imshow(lu2)

    lu3 = setImageColor(rgb_array_blue, 'b')
    plt.subplot2grid((2, 3), (0, 2))
    plt.imshow(lu3)

    lu4 = rgb_array_hist[..., 0].flatten()
    plt.subplot2grid((2, 3), (1, 0))
    plt.hist(lu4, bins=256, range=(0, 256), histtype='stepfilled', color='r', label='Red')
    plt.title("Red")
    plt.xlabel("Value")
    plt.ylabel("Frequency")
    plt.legend()

    lu5 = rgb_array_hist[..., 1].flatten()
    plt.subplot2grid((2, 3), (1, 1))
    plt.hist(lu5, bins=256, range=(0, 256), histtype='stepfilled', color='g', label='Green')
    plt.title("Green")
    plt.xlabel("Value")
    plt.ylabel("Frequency")
    plt.legend()

    lu6 = rgb_array_hist[..., 2].flatten()
    plt.subplot2grid((2, 3), (1, 2))
    plt.hist(lu6, bins=256, range=(0, 256), histtype='stepfilled', color='b', label='Blue')
    plt.title("Blue")
    plt.xlabel("Value")
    plt.ylabel("Frequency")
    plt.legend()

    # plt.hist((rgb_array).ravel(), bins=256, range=(0,1), fc = 'k', ec = 'k')
    plt.show()
项目:coliform-project    作者:uprm-research-resto    | 项目源码 | 文件源码
def savePlot(rgb_array, filename):
    """
    Saves plot data for rgb array
    :param rgb_array: array to be analyzed
    :param filename: file path with filename to save the image. example /pi/plot.jpg
    """
    rgb_array_red = rgb_array * 1
    rgb_array_green = rgb_array * 1
    rgb_array_blue = rgb_array * 1
    rgb_array_hist = rgb_array

    f6 = plt.figure()
    f6.canvas.set_window_title('RGB Plots')

    lu1 = setImageColor(rgb_array_red, 'r')
    plt.subplot2grid((2, 3), (0, 0))
    plt.imshow(lu1)

    lu2 = setImageColor(rgb_array_green, 'g')
    plt.subplot2grid((2, 3), (0, 1))
    plt.imshow(lu2)

    lu3 = setImageColor(rgb_array_blue, 'b')
    plt.subplot2grid((2, 3), (0, 2))
    plt.imshow(lu3)

    lu4 = rgb_array_hist[..., 0].flatten()
    plt.subplot2grid((2, 3), (1, 0))
    plt.hist(lu4, bins=256, range=(0, 256), histtype='stepfilled', color='r', label='Red')
    plt.title("Red")
    plt.xlabel("Value")
    plt.ylabel("Frequency")
    plt.legend()

    lu5 = rgb_array_hist[..., 1].flatten()
    plt.subplot2grid((2, 3), (1, 1))
    plt.hist(lu5, bins=256, range=(0, 256), histtype='stepfilled', color='g', label='Green')
    plt.title("Green")
    plt.xlabel("Value")
    plt.ylabel("Frequency")
    plt.legend()

    lu6 = rgb_array_hist[..., 2].flatten()
    plt.subplot2grid((2, 3), (1, 2))
    plt.hist(lu6, bins=256, range=(0, 256), histtype='stepfilled', color='b', label='Blue')
    plt.title("Blue")
    plt.xlabel("Value")
    plt.ylabel("Frequency")
    plt.legend()

    # plt.hist((rgb_array).ravel(), bins=256, range=(0,1), fc = 'k', ec = 'k')
    f6.savefig(filename)
项目:Primate_Visual_System    作者:pablomc88    | 项目源码 | 文件源码
def PSTH(start_time,time_step,sim_time,recorders,recorded_models,labels,
selected_cell,rows,cols,starting_row,starting_col,trials,PSTHs,bin_size,
visual_stage,path="../../data/"):

    j = 0
    current_row = starting_row
    current_col = starting_col

    for population, model in recorded_models:

        # Single-trial estimation of PSTH
        if trials ==1:

            if(isinstance(selected_cell, list) == False):
                [data,selected_senders,pop] = getData(population,model,recorders,[selected_cell])
            else:
                [data,selected_senders,pop] = getData(population,model,recorders,[selected_cell[j]])

            spike_times = (data[0]['times'])[selected_senders[0]]
            [PSTH_times,PSTH_array] = singleTrialPSTH(start_time,sim_time,spike_times)

        # Standard PSTH
        else:
            PSTH_array = (1000.0/bin_size) * PSTHs[j,int(start_time/bin_size):]/trials
            PSTH_times = np.arange(start_time,sim_time,bin_size)

        # Plot
        if(current_row<rows and current_col<cols):
            Vax = plt.subplot2grid((rows,cols), (current_row,current_col))
#            Vax.plot( PSTH_times, PSTH_array,'b')
            # bar plot
            Vax.bar( PSTH_times, PSTH_array, bin_size, color="blue")
            if trials ==1:
                Vax.plot( spike_times , np.ones(len(spike_times)) ,"r*")
            Vax.set_title(labels[j])

        # save data
        np.savetxt(path+visual_stage+'/data/'+labels[j]+'_PSTH', PSTH_array)

        if j==0:
            np.savetxt(path+visual_stage+'/data/PSTH_times_interp', PSTH_times)

        if(current_col<cols-1):
            current_col+=1
        else:
            current_col = 0
            current_row+=1

        j+=1

    Vax.set_xlabel('time (ms)')

# Spatial tuning curve: it can be either spatial-frequency curve or area-response curve
项目:Primate_Visual_System    作者:pablomc88    | 项目源码 | 文件源码
def receptiveField(fig,N,RF_intervals,s_layers_to_record,labels,RF_bright,RF_dark):

    RF_index = 0

    for interval in RF_intervals:
        counter = 0

        for population, model in s_layers_to_record:

            # 3D plot
#            Vax = fig.add_subplot(len(s_layers_to_record),len(RF_intervals),1 +\
#            RF_index + counter*len(RF_intervals), projection='3d')
#            X = np.arange(N)
#            Y = X
#            X, Y = np.meshgrid(X, Y)
#            Z = RF_bright[RF_index,counter,:,:] - RF_dark[RF_index,counter,:,:]
#            # Interpolation
#            sigma = 1.5
#            Z_inter = gaussian_filter(Z, sigma)
#            # Plot
#            im_plot = Vax.plot_surface(X, Y, Z_inter, rstride=1, cstride=1, cmap='coolwarm',
#                                   linewidth=0, antialiased=False)

            # 2D plot
#            Vax = plt.subplot2grid((len(s_layers_to_record),len(RF_intervals)),(counter,RF_index))
#            im_plot = Vax.matshow(RF_bright[RF_index,counter,:,:] - RF_dark[RF_index,counter,:,:])

            # Contour Plot
            Vax = plt.subplot2grid((len(s_layers_to_record),len(RF_intervals)),(counter,RF_index))
            X = np.arange(N)
            Y = X
            X, Y = np.meshgrid(X, Y)
            Z = RF_bright[RF_index,counter,:,:] - RF_dark[RF_index,counter,:,:]
            # Interpolation
            sigma = 1.5
            Z_inter = gaussian_filter(Z, sigma)
            # Plot
            im_plot = Vax.contourf(X, Y, Z_inter, 10, cmap=plt.cm.coolwarm)

            # axis, title
            Vax.axes.get_xaxis().set_ticks([])
            Vax.axes.get_yaxis().set_ticks([])

            if RF_index == 0:
                Vax.set_title(str(labels[counter] +'\n'+ str(RF_intervals[RF_index])))
            else:
                Vax.set_title(str(RF_intervals[RF_index]))

            cbar = fig.colorbar(im_plot)

            counter+=1

        RF_index+=1

# Show a video sequence of the input stimulus
项目:Primate_Visual_System    作者:pablomc88    | 项目源码 | 文件源码
def LFP(plot_type,LFP_records,trials,start_time,time_step,sim_time,recorded_models,
PSTHs,top_PSTH_index,bin_size,labels,rows,cols,starting_row,starting_col,visual_stage,
layer_sizes,path = '../../data/'):

    j = 0
    spike_j = 0
    current_row = starting_row
    current_col = starting_col

    for population, model in recorded_models:

        if(current_row<rows and current_col<cols):
            Vax = plt.subplot2grid((rows,cols), (current_row,current_col))

            # Membrane potential and synaptic currents
            if plot_type < 3:
                average_record = LFP_records[plot_type,j,:] / trials
                y = average_record[int(start_time/time_step):len(average_record)]
                time = np.arange(start_time,sim_time+time_step,time_step)
                time = time[0:len(y)]

            # Firing rates
            else:
                if model == 'retina_parvo_ganglion_cell' or model=='LGN_relay_cell' or\
                model == 'LGN_interneuron' or model=='Cortex_excitatory_cell' or\
                model=='Cortex_inhibitory_cell':
                    # List of cell IDs
                    if(isinstance(layer_sizes, list) == False):
                        cell_list = np.arange(layer_sizes**2)
                    else:
                        cell_list = np.arange(layer_sizes[j])

                    average_record = (1000.0/bin_size) *\
                    np.sum(PSTHs[:,top_PSTH_index[spike_j],:],axis=0) / (trials * len(cell_list))

                    y = average_record[int(start_time/bin_size):len(average_record)]
                    time = np.arange(start_time,sim_time,bin_size)

                    spike_j+=1

                else:
                    y = np.zeros(2)
                    time = np.zeros(2)

            Vax.plot(time,y)
            Vax.set_title(labels[j])

        # save data
        np.savetxt(path+visual_stage+'/data/'+labels[j]+'_'+str(plot_type), y)
        if j==0:
            np.savetxt(path+visual_stage+'/data/time', time)

        if(current_col<cols-1):
            current_col+=1
        else:
            current_col = 0
            current_row+=1

        j+=1

    Vax.set_xlabel('time (ms)')