Python matplotlib.pyplot.setp() Examples

The following are code examples for showing how to use matplotlib.pyplot.setp(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: DDEA-DEV   Author: TinyOS-Camp   File: radar_chart.py    GNU General Public License v2.0 7 votes vote down vote up
def subplot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'):
    #def subplot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'):
    num_of_picks=9
    theta = radar_factory(len(spoke_labels), frame='circle')
    fig = plt.figure(figsize=(num_of_picks, num_of_picks))
    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
    num_col=np.floor(np.sqrt(len(data)))
    num_row=np.ceil(num_of_picks/num_col)
    for k,(data_col,sensor_label_) in enumerate(zip(data,sensor_labels)):
        #subplot(num_col,num_row,i+1)
        ax = fig.add_subplot(num_col,num_row,k+1, projection="radar")
        ax.plot(theta, data_col)
        ax.fill(theta, data_col, alpha=0.2)
        ax.set_varlabels(spoke_labels)
        #plt.title(sensor_label_,fontsize='small')
        legend = plt.legend([sensor_label_], loc=(-0.2, 1.1), labelspacing=0.01)
        plt.setp(legend.get_texts(), fontsize='small')
        radar_bnd=max(max(data))
        #import pdb;pdb.set_trace()
        rgrid_spacing=np.round(list(np.arange(0.1,radar_bnd,float(radar_bnd)/5)),2)
        plt.rgrids(rgrid_spacing)
        #plt.rgrids([0.1 + 2*i / 10.0 for i in range(radar_bnd)])
        ##radar_chart.plot(data_col, spoke_labels, sensor_label_, saveto="time_radar.png",frame_type='circle')    
    if saveto != None:
        plt.savefig(saveto) 
Example 2
Project: CrossLingualDepParser   Author: uclanlp   File: distance.py    GNU General Public License v3.0 6 votes vote down vote up
def draw_heatmap(arr, xs, ys):
    fig, ax = plt.subplots()
    im = ax.imshow(arr)
    #
    ax.set_xticks(np.arange(len(xs)))
    ax.set_yticks(np.arange(len(ys)))
    ax.set_xticklabels(xs)
    ax.set_yticklabels(ys)
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
         rotation_mode="anchor")
    for i in range(len(xs)):
        for j in range(len(ys)):
            text = ax.text(j, i, "%.1f"%(arr[i, j]*100),
                           ha="center", va="center", color="w")
    fig.tight_layout()
    plt.show() 
Example 3
Project: gdf   Author: GeoscienceAustralia   File: _gdfutils.py    Apache License 2.0 6 votes vote down vote up
def plotImages(arrays):
    img = arrays
    num_t = img.shape[0]
    num_rowcol = math.ceil(math.sqrt(num_t))
    fig = plt.figure()
    fig.clf()
    plot_count = 1
    for i in range(img.shape[0]):
        data = img[i]
        ax = fig.add_subplot(num_rowcol, num_rowcol, plot_count)
        plt.setp(ax, xticks=[], yticks=[])
        cax = ax.imshow(data, interpolation='nearest', aspect = 'equal')
        #fig.colorbar(cax)
        plot_count += 1
    fig.tight_layout()
    plt.show() 
Example 4
Project: inverse-bgo   Author: PredictiveScienceLab   File: _core.py    MIT License 6 votes vote down vote up
def plot_summary(f, X_design, model, prefix, G, Gamma_name):
    """
    Plot a summary of the current iteration.
    """
    import matplotlib.pyplot as plt
    X = model.X
    y = model.Y
    m_s, k_s = model.predict(X_design, full_cov=True)
    m_05, m_95 = model.predict_quantiles(X_design)
    fig, ax1 = plt.subplots()
    ax1.plot(X_design, f(X_design), 'b', linewidth=2)
    ax1.plot(X, y, 'go', linewidth=2, markersize=10, markeredgewidth=2)
    ax1.plot(X_design, m_s, 'r--', linewidth=2)
    ax1.fill_between(X_design.flatten(), m_05.flatten(), m_95.flatten(),
                     color='grey', alpha=0.5)
    ax1.set_ylabel('$f(x)$', fontsize=16)
    ax2 = ax1.twinx()
    ax2.plot(X_design, G, 'g', linewidth=2)
    ax2.set_ylabel('$%s(x)$' % Gamma_name, fontsize=16, color='g')
    #ax2.set_ylim([0., 3.])
    plt.setp(ax2.get_yticklabels(), color='g')
    png_file = prefix + '.png'
    print 'Writing:', png_file
    plt.savefig(png_file)
    plt.clf() 
Example 5
Project: DDEA-DEV   Author: TinyOS-Camp   File: radar_chart.py    GNU General Public License v2.0 6 votes vote down vote up
def plot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'):
    theta = radar_factory(len(spoke_labels), frame=frame_type)
    fig = plt.figure(figsize=(9, 9))
    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
    ax = fig.add_subplot(111, projection="radar")
    plt.rgrids([np.round(0.1 + i / 10.0,2) for i in range(10)])
    for d in data:
        ax.plot(theta, d)
        ax.fill(theta, d, alpha=0.2)
    
    ax.set_varlabels(spoke_labels)
    
    legend = plt.legend(sensor_labels, loc=(0.0, 0.9), labelspacing=0.1)
    plt.setp(legend.get_texts(), fontsize='small')
    
    if saveto != None:
        plt.savefig(saveto) 
Example 6
Project: DDEA-DEV   Author: TinyOS-Camp   File: radar_chart.py    GNU General Public License v2.0 6 votes vote down vote up
def subplot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'):
    #def subplot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'):
    num_of_picks=9
    theta = radar_factory(len(spoke_labels), frame='circle')
    fig = plt.figure(figsize=(num_of_picks, num_of_picks))
    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
    num_col=np.floor(np.sqrt(len(data)))
    num_row=np.ceil(num_of_picks/num_col)
    for k,(data_col,sensor_label_) in enumerate(zip(data,sensor_labels)):
        #subplot(num_col,num_row,i+1)
        ax = fig.add_subplot(num_col,num_row,k+1, projection="radar")
        ax.plot(theta, data_col)
        ax.fill(theta, data_col, alpha=0.2)
        ax.set_varlabels(spoke_labels)
        #plt.title(sensor_label_,fontsize='small')
        legend = plt.legend([sensor_label_], loc=(-0.2, 1.1), labelspacing=0.01)
        plt.setp(legend.get_texts(), fontsize='small')
        radar_bnd=max(max(data))
        #import pdb;pdb.set_trace()
        rgrid_spacing=np.round(list(np.arange(0.1,radar_bnd,float(radar_bnd)/5)),2)
        plt.rgrids(rgrid_spacing)
        #plt.rgrids([0.1 + 2*i / 10.0 for i in range(radar_bnd)])
        ##radar_chart.plot(data_col, spoke_labels, sensor_label_, saveto="time_radar.png",frame_type='circle')    
    if saveto != None:
        plt.savefig(saveto) 
Example 7
Project: DDEA-DEV   Author: TinyOS-Camp   File: radar_chart.py    GNU General Public License v2.0 6 votes vote down vote up
def plot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'):
    theta = radar_factory(len(spoke_labels), frame=frame_type)
    fig = plt.figure(figsize=(9, 9))
    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
    ax = fig.add_subplot(111, projection="radar")
    plt.rgrids([np.round(0.1 + i / 10.0,2) for i in range(10)])
    for d in data:
        ax.plot(theta, d)
        ax.fill(theta, d, alpha=0.2)
    
    ax.set_varlabels(spoke_labels)
    
    legend = plt.legend(sensor_labels, loc=(0.0, 0.9), labelspacing=0.1)
    plt.setp(legend.get_texts(), fontsize='small')
    
    if saveto != None:
        plt.savefig(saveto) 
Example 8
Project: DDEA-DEV   Author: TinyOS-Camp   File: radar_chart.py    GNU General Public License v2.0 6 votes vote down vote up
def plot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'):
    theta = radar_factory(len(spoke_labels), frame=frame_type)
    fig = plt.figure(figsize=(9, 9))
    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
    ax = fig.add_subplot(111, projection="radar")
    plt.rgrids([np.round(0.1 + i / 10.0,2) for i in range(10)])
    for d in data:
        ax.plot(theta, d)
        ax.fill(theta, d, alpha=0.2)
    
    ax.set_varlabels(spoke_labels)
    
    legend = plt.legend(sensor_labels, loc=(0.0, 0.9), labelspacing=0.1)
    plt.setp(legend.get_texts(), fontsize='small')
    
    if saveto != None:
        plt.savefig(saveto) 
Example 9
Project: DDEA-DEV   Author: TinyOS-Camp   File: radar_chart.py    GNU General Public License v2.0 6 votes vote down vote up
def plot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'):
    theta = radar_factory(len(spoke_labels), frame=frame_type)
    fig = plt.figure(figsize=(9, 9))
    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
    ax = fig.add_subplot(111, projection="radar")
    plt.rgrids([np.round(0.1 + i / 10.0,2) for i in range(10)])
    for d in data:
        ax.plot(theta, d)
        ax.fill(theta, d, alpha=0.2)
    
    ax.set_varlabels(spoke_labels)
    
    legend = plt.legend(sensor_labels, loc=(0.0, 0.9), labelspacing=0.1)
    plt.setp(legend.get_texts(), fontsize='small')
    
    if saveto != None:
        plt.savefig(saveto) 
Example 10
Project: DDEA-DEV   Author: TinyOS-Camp   File: radar_chart.py    GNU General Public License v2.0 6 votes vote down vote up
def subplot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'):
    #def subplot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'):
    num_of_picks=9
    theta = radar_factory(len(spoke_labels), frame='circle')
    fig = plt.figure(figsize=(num_of_picks, num_of_picks))
    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
    num_col=np.floor(np.sqrt(len(data)))
    num_row=np.ceil(num_of_picks/num_col)
    for k,(data_col,sensor_label_) in enumerate(zip(data,sensor_labels)):
        #subplot(num_col,num_row,i+1)
        ax = fig.add_subplot(num_col,num_row,k+1, projection="radar")
        ax.plot(theta, data_col)
        ax.fill(theta, data_col, alpha=0.2)
        ax.set_varlabels(spoke_labels)
        #plt.title(sensor_label_,fontsize='small')
        legend = plt.legend([sensor_label_], loc=(-0.2, 1.1), labelspacing=0.01)
        plt.setp(legend.get_texts(), fontsize='small')
        radar_bnd=max(max(data))
        #import pdb;pdb.set_trace()
        rgrid_spacing=np.round(list(np.arange(0.1,radar_bnd,float(radar_bnd)/5)),2)
        plt.rgrids(rgrid_spacing)
        #plt.rgrids([0.1 + 2*i / 10.0 for i in range(radar_bnd)])
        ##radar_chart.plot(data_col, spoke_labels, sensor_label_, saveto="time_radar.png",frame_type='circle')    
    if saveto != None:
        plt.savefig(saveto) 
Example 11
Project: DDEA-DEV   Author: TinyOS-Camp   File: radar_chart.py    GNU General Public License v2.0 6 votes vote down vote up
def plot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'):
    theta = radar_factory(len(spoke_labels), frame=frame_type)
    fig = plt.figure(figsize=(9, 9))
    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
    ax = fig.add_subplot(111, projection="radar")
    plt.rgrids([np.round(0.1 + i / 10.0,2) for i in range(10)])
    for d in data:
        ax.plot(theta, d)
        ax.fill(theta, d, alpha=0.2)
    
    ax.set_varlabels(spoke_labels)
    
    legend = plt.legend(sensor_labels, loc=(0.0, 0.9), labelspacing=0.1)
    plt.setp(legend.get_texts(), fontsize='small')
    
    if saveto != None:
        plt.savefig(saveto) 
Example 12
Project: DDEA-DEV   Author: TinyOS-Camp   File: radar_chart.py    GNU General Public License v2.0 6 votes vote down vote up
def subplot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'):
    #def subplot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'):
    num_of_picks=9
    theta = radar_factory(len(spoke_labels), frame='circle')
    fig = plt.figure(figsize=(num_of_picks, num_of_picks))
    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
    num_col=np.floor(np.sqrt(len(data)))
    num_row=np.ceil(num_of_picks/num_col)
    for k,(data_col,sensor_label_) in enumerate(zip(data,sensor_labels)):
        #subplot(num_col,num_row,i+1)
        ax = fig.add_subplot(num_col,num_row,k+1, projection="radar")
        ax.plot(theta, data_col)
        ax.fill(theta, data_col, alpha=0.2)
        ax.set_varlabels(spoke_labels)
        #plt.title(sensor_label_,fontsize='small')
        legend = plt.legend([sensor_label_], loc=(-0.2, 1.1), labelspacing=0.01)
        plt.setp(legend.get_texts(), fontsize='small')
        radar_bnd=max(max(data))
        #import pdb;pdb.set_trace()
        rgrid_spacing=np.round(list(np.arange(0.1,radar_bnd,float(radar_bnd)/5)),2)
        plt.rgrids(rgrid_spacing)
        #plt.rgrids([0.1 + 2*i / 10.0 for i in range(radar_bnd)])
        ##radar_chart.plot(data_col, spoke_labels, sensor_label_, saveto="time_radar.png",frame_type='circle')    
    if saveto != None:
        plt.savefig(saveto) 
Example 13
Project: DDEA-DEV   Author: TinyOS-Camp   File: radar_chart.py    GNU General Public License v2.0 6 votes vote down vote up
def plot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'):
    theta = radar_factory(len(spoke_labels), frame=frame_type)
    fig = plt.figure(figsize=(9, 9))
    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
    ax = fig.add_subplot(111, projection="radar")
    plt.rgrids([np.round(0.1 + i / 10.0,2) for i in range(10)])
    for d in data:
        ax.plot(theta, d)
        ax.fill(theta, d, alpha=0.2)
    
    ax.set_varlabels(spoke_labels)
    
    legend = plt.legend(sensor_labels, loc=(0.0, 0.9), labelspacing=0.1)
    plt.setp(legend.get_texts(), fontsize='small')
    
    if saveto != None:
        plt.savefig(saveto) 
Example 14
Project: QuantStudio   Author: Scorpi000   File: IC.py    GNU General Public License v3.0 6 votes vote down vote up
def genMatplotlibFig(self, file_path=None):
        Fig, Axes = plt.subplots(figsize=(16, 8))
        xData = np.arange(0, self._Output["统计数据"].shape[0])
        xTickLabels = [str(i) for i in self._Output["统计数据"].index]
        yMajorFormatter = FuncFormatter(_QS_formatMatplotlibPercentage)
        Axes.yaxis.set_major_formatter(yMajorFormatter)
        Axes.bar(xData, self._Output["统计数据"]["IC平均值"].values, label="IC", color="b")
        Axes.set_xticks(xData)
        Axes.set_xticklabels(xTickLabels)
        Axes.legend(loc='upper left')
        RAxes = Axes.twinx()
        RAxes.yaxis.set_major_formatter(yMajorFormatter)
        RAxes.plot(xData, self._Output["统计数据"]["胜率"].values, label="胜率", color="r", alpha=0.6, lw=3)
        RAxes.legend(loc="upper right")
        plt.setp(Axes.get_xticklabels(), visible=True, rotation=0, ha='center')
        if file_path is not None: Fig.savefig(file_path, dpi=150, bbox_inches='tight')
        return Fig 
Example 15
Project: uiKLine   Author: rjj510   File: visFunction.py    MIT License 6 votes vote down vote up
def plotSigHeats(signals,markets,start=0,step=2,size=1,iters=6):
    """
    打印信号回测盈损热度图,寻找参数稳定岛
    """
    sigMat = pd.DataFrame(index=range(iters),columns=range(iters))
    for i in range(iters):
        for j in range(iters):
            climit = start + i*step
            wlimit = start + j*step
            caps,poss = plotSigCaps(signals,markets,climit=climit,wlimit=wlimit,size=size,op=False)
            sigMat[i][j] = caps[-1]
    sns.heatmap(sigMat.values.astype(np.float64),annot=True,fmt='.2f',annot_kws={"weight": "bold"})
    xTicks   = [i+0.5 for i in range(iters)]
    yTicks   = [iters-i-0.5 for i in range(iters)]
    xyLabels = [str(start+i*step) for i in range(iters)]
    _, labels = plt.yticks(yTicks,xyLabels)
    plt.setp(labels, rotation=0)
    _, labels = plt.xticks(xTicks,xyLabels)
    plt.setp(labels, rotation=90)
    plt.xlabel('Loss Stop @')
    plt.ylabel('Profit Stop @')
    return sigMat 
Example 16
Project: q-learning   Author: nlinker   File: plotting.py    MIT License 6 votes vote down vote up
def build_stats_plot(stats: Stats, smoothing_window=10):

    fig = plt.figure(figsize=(10, 15))
    plt.figure(figsize=(15, 10), facecolor="w")
    # noinspection PyTypeChecker
    ax1: Axes = plt.subplot(2, 1, 1)
    # noinspection PyTypeChecker
    ax2: Axes = plt.subplot(2, 1, 2, sharex=ax1)

    # plot the episode length over time
    ax1.plot(stats.episode_lengths)

    # plot the rewards value over time (smoothed)
    rewards_smoothed = pd.Series(stats.episode_rewards) \
        .rolling(smoothing_window, min_periods=smoothing_window).mean()
    ax2.plot(rewards_smoothed)

    ax2.set_xlabel("Episodes")
    ax1.set_ylabel("Episode length")
    ax2.set_ylabel("Episode Reward (Smoothed)")
    plt.setp(ax1.get_xticklabels(), visible=False)

    return fig 
Example 17
Project: dgl   Author: dmlc   File: viz.py    Apache License 2.0 6 votes vote down vote up
def draw_heatmap(array, input_seq, output_seq, dirname, name):
    dirname = os.path.join('log', dirname)
    if not os.path.exists(dirname):
        os.makedirs(dirname)

    fig, axes = plt.subplots(2, 4)
    cnt = 0
    for i in range(2):
        for j in range(4):
            axes[i, j].imshow(array[cnt].transpose(-1, -2))
            axes[i, j].set_yticks(np.arange(len(input_seq)))
            axes[i, j].set_xticks(np.arange(len(output_seq)))
            axes[i, j].set_yticklabels(input_seq, fontsize=4)
            axes[i, j].set_xticklabels(output_seq, fontsize=4)
            axes[i, j].set_title('head_{}'.format(cnt), fontsize=10)
            plt.setp(axes[i, j].get_xticklabels(), rotation=45, ha="right",
                     rotation_mode="anchor")
            cnt += 1

    fig.suptitle(name, fontsize=12)
    plt.tight_layout()
    plt.savefig(os.path.join(dirname, '{}.pdf'.format(name)))
    plt.close() 
Example 18
Project: hoaxy-network   Author: shaochengcheng   File: plot.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_kcore_timeline(fn='k_core_evolution.csv'):
    df = pd.read_csv(fn, parse_dates=['timeline'])
    m = df.mcore_num.groupby(df.mcore_k).max()
    m.index = df.timeline.groupby(df.mcore_k).first().values

    fig, ax = plt.subplots(figsize=(4, 3))
    ax2 = ax.twinx()
    l1, = ax2.plot(df.timeline.values, df.mcore_k, color='b')
    ax2.set_ylabel('k')
    l2, = ax.plot(m.index.values, m.values, color='r')
    ax.set_ylabel('n')
    labels = ax.get_xticklabels()
    plt.setp(labels, rotation=-30, fontsize=10)
    plt.legend([l1, l2], ['k of Main Cores', 'Size of Main Cores n'])
    plt.tight_layout()
    plt.savefig('k-core.pdf') 
Example 19
Project: jMetalPy   Author: jMetal   File: chord_plot.py    MIT License 6 votes vote down vote up
def hover_over_bin(event, handle_tickers, handle_plots, colors, fig):
    is_found = False

    for iobj in range(len(handle_tickers)):
        for ibin in range(len(handle_tickers[iobj])):
            cont = False
            if not is_found:
                cont, ind = handle_tickers[iobj][ibin].contains(event)
                if cont:
                    is_found = True
            if cont:
                plt.setp(handle_tickers[iobj][ibin], facecolor=colors[iobj])
                [h.set_visible(True) for h in handle_plots[iobj][ibin]]
                is_found = True
                fig.canvas.draw_idle()
            else:
                plt.setp(handle_tickers[iobj][ibin], facecolor=(1, 1, 1))
                for h in handle_plots[iobj][ibin]:
                    h.set_visible(False)
                fig.canvas.draw_idle() 
Example 20
Project: spatial_patterns   Author: sim-web   File: figures.py    GNU General Public License v3.0 6 votes vote down vote up
def empty_plot_with_size_bar(self, gridspec, sizelabel):
		"""
		Adds an empty plot with the x axis as a size bar

		Parameters
		----------
		gridspec : gridspec
		sizelabel : str
			This label is place in the center
		"""
		plt.subplot(gridspec)
		plt.plot([0, 1], alpha=0)
		ax = plt.gca()
		trans = mpl.transforms.blended_transform_factory(
							ax.transAxes, ax.transAxes)
		plt.annotate(
			 '', xy=(0, 0), xycoords=trans,
			xytext=(1, 0), textcoords=trans,
			arrowprops={'arrowstyle': '<->', 'shrinkA': 1, 'shrinkB': 1,
						'lw':1.5,
						'mutation_scale': 10., 'color': 'black'})
		general_utils.plotting.remove_all_ticks(ax)
		general_utils.plotting.invisible_axis(ax)
		plt.setp(ax, xticks=[0.5], xticklabels=[sizelabel]) 
Example 21
Project: MiaSeg   Author: jajenQin   File: Miaimshow.py    GNU General Public License v3.0 6 votes vote down vote up
def subplots(images,num,cols,figsize=(8,9), colormap=plt.cm.gray):
    #fig, axes = plt.subplots(nrows=rows, ncols=cols, figsize=figsize)
    fig=plt.figure(num=num,figsize=figsize)
    images=np.squeeze(images)
    ax=[]
    #plt.setp(axes.flat, xticks=[], yticks=[])
    Numimgs=images.shape[0]
    gs = gridspec.GridSpec(Numimgs // cols, cols)
    for i in range(Numimgs):
        row = (i // cols)
        col = i % cols
        ax.append(fig.add_subplot(gs[row, col]))
        img = images[i,:, :]
        #axlog[-1].set_title('markevery=%s' % str(case))
        #ax[-1].set_xscale('log')
        #ax[-1].set_yscale('log')
        ax[-1].imshow(img.astype(np.uint8), cmap=colormap)
        ax[-1].axis('off')
    plt.tight_layout(pad=0.01, w_pad=0.01, h_pad=0.01)
   # fig.subplots_adjust(bottom=0.05, right=0.95)

    plt.show() 
Example 22
Project: tomato   Author: sertansenturk   File: plotter.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _plot_melodic_progression(ax3, melodic_progression, pitch,
                                  pitch_distribution):
        try:
            # plot...
            AudioSeyirAnalyzer.plot(melodic_progression, ax3)

            # axis style
            ax3.set_xlabel('')  # remove the automatically given labels
            ax3.set_ylabel('')
            plt.setp(ax3.get_yticklabels(), visible=False)
            plt.setp(ax3.get_xticklabels(), visible=False)

            # set xlim to the last time in the pitch track
            ax3.set_xlim([pitch[0, 0], pitch[-1, 0]])
            ax3.set_ylim([np.min(pitch_distribution.bins),
                          np.max(pitch_distribution.bins)])

            # remove the spines from the third subplot
            ax3.spines['bottom'].set_visible(False)
            ax3.spines['left'].set_visible(False)
            ax3.spines['right'].set_visible(False)
            ax3.get_yaxis().set_ticks([])
        except TypeError:
            logger.debug('The melodic progression is not computed.') 
Example 23
Project: pisa   Author: IceCubeOpenSource   File: plotter.py    Apache License 2.0 6 votes vote down vote up
def plot_1d_cmp(self, map_sets, plot_axis, fname=None, **kwargs):
        """1d comparisons for two map_sets as projections"""
        for i in range(len(map_sets[0])):
            maps = [map_set[i] for map_set in map_sets]
            self.stamp = maps[0].tex
            for k, map_set in enumerate(map_sets):
                maps[k].tex = map_set.tex
            self.init_fig()
            if self.ratio:
                ax1 = plt.subplot2grid((4, 1), (0, 0), rowspan=3)
                plt.setp(ax1.get_xticklabels(), visible=False)
            self.reset_colors()
            for map in maps:
                self.next_color()
                self.plot_1d_projection(map, plot_axis, **kwargs)
            self.add_stamp()
            self.add_leg()
            if self.ratio:
                plt.subplot2grid((4, 1), (3, 0), sharex=ax1)
                #self.plot_1d_ratio(maps, plot_axis, r_vmin=0.1, r_vmax=0.1, **kwargs)
                self.plot_1d_ratio(maps, plot_axis, **kwargs)
            self.dump('%s_%s'%(fname, maps[0].name))

    # --- plotting core functions --- 
Example 24
Project: MCS_DTW   Author: CGuichardMasterDL   File: dtw.py    MIT License 5 votes vote down vote up
def etude_d_max_diagonale(sounds):
    """
        Appliquer find_d_max_diagonale pour chaque couple de valeurs de la base en paramètre
        le représenter dans matplotlib
    """
    x_ticks = []
    matrix = []
    for x_sound in sounds:
        x_ticks.append(x_sound.get_locuteur()+" : "+x_sound.get_ordre())
        matrix_line = []
        for y_sound in sounds:
            matrix_line.append(find_d_max_diagonale(
                x_sound.get_mfcc(), y_sound.get_mfcc()))
        matrix.append(matrix_line)
    matrix = np.asarray(np.asarray(matrix))

    _, axes = plt.subplots()

    ims = axes.imshow(matrix, interpolation='nearest', cmap=plt.cm.Reds) # pylint: disable=E1101
    axes.figure.colorbar(ims, ax=axes)

    axes.set(xticks=np.arange(matrix.shape[1]),
             yticks=np.arange(matrix.shape[0]))

    axes.set_yticklabels(x_ticks, fontsize=7)
    axes.set_xticklabels(x_ticks, fontsize=7)
    axes.set_title("Distance maximale de la diagonale")
    plt.setp(axes.get_xticklabels(), rotation=45, ha="right",
             rotation_mode="anchor")
    for i in range(matrix.shape[0]):
        for j in range(matrix.shape[1]):
            axes.text(j, i, format(matrix[i, j], 'd'),
                      ha="center", va="center")

    plt.show() 
Example 25
Project: scicast   Author: iandriver   File: matrix_filter.py    MIT License 5 votes vote down vote up
def log2_oulierfilter(df_by_cell, plot=False):
        log2_df = np.log2(df_by_cell+1)
        top_log2 = find_top_common_genes(log2_df)
        if all(top_log2) != 0:
            log2_df2= pd.to_numeric(pd.DataFrame(log2_df), errors='coerce')
            log_mean = top_log2.mean(axis=0).sort_values(ascending=False)
            log2_sorted = top_log2.reindex_axis(top_log2.mean(axis=0).sort_values(ascending=False).index, axis=1)
            xticks = []
            keep_col= []
            log2_cutoff = np.average(np.average(log2_sorted))-2*np.average(np.std(log2_sorted))
            for col, m in zip(log2_sorted.columns.tolist(),log2_sorted.mean()):
                if m > log2_cutoff:
                    keep_col.append(col)
                    xticks.append(col+' '+str("%.2f" % m))
            excluded_cells = [x for x in log2_sorted.columns.tolist() if x not in keep_col]
            filtered_df_by_cell = df_by_cell[keep_col]
            filtered_df_by_gene = filtered_df_by_cell.transpose()
            filtered_log2 = np.log2(filtered_df_by_cell[filtered_df_by_cell>0])
            if plot:
                ax = sns.boxplot(data=filtered_log2, whis= .75, notch=True)
                ax = sns.stripplot(x=filtered_log2.columns.values, y=filtered_log2.mean(axis=0), size=4, jitter=True, edgecolor="gray")
                xtickNames = plt.setp(ax, xticklabels=xticks)
                plt.setp(xtickNames, rotation=90, fontsize=9)
                plt.show()
                plt.clf()
                sns.distplot(filtered_log2.mean())
                plt.show()
            log2_expdf_cell = np.log2(filtered_df_by_cell+1)
            log2_expdf_gene = log2_expdf_cell.transpose()
            return log2_expdf_cell, log2_expdf_gene
        else:
            print("no common genes found")
            return log2_df, log2_df.transpose() 
Example 26
Project: DETAD   Author: HumamAlwassel   File: false_postive_analysis.py    MIT License 5 votes vote down vote up
def subplot_fp_profile(fig, ax, values, labels, colors, xticks, xlabel, ylabel, title,
                       fontsize=14, bottom=0, top=100, bar_width=1, spacing=0.85,
                       grid_color='gray', grid_linestyle=':', grid_lw=1, 
                       ncol=1, legend_loc='best'):

    ax.yaxis.grid(color=grid_color, linestyle=grid_linestyle, lw=grid_lw)
    
    cumsum_values = np.cumsum(np.array(values)*100, axis=1)    
    index = np.linspace(0, spacing*bar_width*len(values),len(values))
    for i in range(cumsum_values.shape[1])[::-1]:
        rects1 = ax.bar(index, cumsum_values[:,i], bar_width,
                         capsize = i,
                         color=colors[i],
                         label=xticks[i], zorder=0)

    lgd = ax.legend(loc=legend_loc, ncol=ncol, fontsize=fontsize/1.2, edgecolor='k')
    
    ax.set_ylabel(ylabel, fontsize=fontsize)
    ax.set_xlabel(xlabel, fontsize=fontsize)
    plt.setp(ax.get_yticklabels(), fontsize=fontsize/1.2)
    plt.xticks(np.array(index), np.array(labels[:len(values)]), fontsize=fontsize/1.2, rotation=90)
    plt.yticks(np.linspace(0,1,11)*100, fontsize=fontsize/1.2 )
    ax.set_ylim(bottom=bottom, top=top)
    ax.set_xlim(left=index[0]-1.25*bar_width, right=index[-1]+1.0*bar_width)
    ax.set_title(title, fontsize=fontsize)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.yaxis.grid(True, linestyle='dotted')
    ax.set_axisbelow(True)
    ax.yaxis.set_tick_params(size=10, direction='in', width=2)
    for axis in ['bottom','left']:
        ax.spines[axis].set_linewidth(2.5)

    return lgd 
Example 27
Project: matplotlib_utilities   Author: dmccloskey   File: matplot.py    MIT License 5 votes vote down vote up
def boxAndWhiskersPlot(self,title_I,xticklabels_I,ylabel_I,xlabel_I,data_I,mean_I=None,ci_I=None,filename_I=None,show_plot_I=True,bootstrap_I=5000,notch_I = 0):
        '''generates a box and whiskers plot using the mean instead of the median
        default: Make a box and whisker plot for each column of data_I or each vector in sequence data_I.
                 The box extends from the lower to upper quartile values of the data, with a line at the median.
                 The whiskers extend from the box to show the range of the data.
                 Flier points are those past the end of the whiskers.
        mean_I: defines the median
        ci_I and notch_I: defines the notch confidence intervals
        Use case 1: set the whiskers to the 95% confidence intervals and median to the mean
                    data_I = [[ci_lb,ci_ub,mean],...]'''

        whiskers_I=[5,95]
        ha = ['right', 'center', 'left']
        try:
            fig, ax = plt.subplots()
            pos = numpy.array(list(range(len(data_I))))+1
            bp = ax.boxplot(data_I, sym='k+', #whis=whiskers_I,
                            positions=pos,
                            notch=notch_I, bootstrap=bootstrap_I,
                            usermedians=mean_I,
                            conf_intervals=ci_I)

            ax.set_xlabel(xlabel_I)
            ax.set_ylabel(ylabel_I)
            ax.set_xticklabels(xticklabels_I, size=6, rotation=15, ha=ha[1])
            ax.set_title(title_I)
            plt.setp(bp['whiskers'], color='k',  linestyle='-' )
            plt.setp(bp['fliers'], markersize=3.0)
            # Produce an image.
            if filename_I:
                fig.savefig(filename_I)
            # Show the image.
            if show_plot_I:
                plt.show();
        except IndexError as e:
            print(e); 
Example 28
Project: mac-network   Author: stanfordnlp   File: visualization.py    Apache License 2.0 5 votes vote down vote up
def showTableAtt(instance, table, x, y, name):
    # if args.trans:
    #     figureTableDims = (len(y) / 2 + 4, len(x) + 2)
    # else:
    #     figureTableDims = (len(y) / 2, len(x) / 2)
    # xx = np.arange(0, len(x), 1)
    # yy = np.arange(0, len(y), 1)
    # extent2 = np.min(xx), np.max(xx), np.min(yy), np.max(yy)
    
    fig2, bx = plt.subplots(1, 1) # figsize = figureTableDims
    bx.cla()

    sns.set(font_scale = fontScale)

    if args.trans:
        table = np.transpose(table)
        x, y = y, x
    
    tableMap = pandas.DataFrame(data = table, index = x, columns = y)
    
    bx = sns.heatmap(tableMap, cmap = "Purples", cbar = False, linewidths = .5, linecolor = "gray", square = True)
    
    # x ticks
    if args.trans:
        bx.xaxis.tick_top()
    locs, labels = plt.xticks()
    if args.trans:
        plt.setp(labels, rotation = 0)
    else:
        plt.setp(labels, rotation = 60)

    # y ticks
    locs, labels = plt.yticks()
    plt.setp(labels, rotation = 0)

    plt.savefig(outTableAttName(instance, name), dpi = 720) 
Example 29
Project: tmatplot   Author: taehoonlee   File: basics.py    MIT License 5 votes vote down vote up
def corr(data, xlabel=None, ylabel=None,
         title=None, colorbar=True,
         window=None, sample=1000,
         savefile=None, close=True, figsize=(8, 6)):
    plt.figure(figsize=figsize)
    if window is not None:
        corrcoef = []
        for s in range(sample):
            i = np.random.randint(0, data.shape[0]-window)
            c = np.corrcoef(data[i:(i+window)].T)
            corrcoef.append(c)
        results = np.nanmean(np.array(corrcoef), axis=0)
    else:
        results = np.corrcoef(data[np.sum(np.isnan(data), axis=1) == 0].T)
    plt.imshow(results)

    if title is not None:
        plt.title(title)

    if xlabel is None:
        plt.setp(plt.gca().get_xticklabels(), visible=False)

    if ylabel is None:
        plt.setp(plt.gca().get_yticklabels(), visible=False)
    else:
        yticks = [x.astype(int) for x in plt.gca().get_yticks()]
        if yticks[0] < 0:
            yticks = np.delete(yticks, 0)
        if yticks[-1] >= len(ylabel):
            yticks = np.delete(yticks, -1)
        plt.gca().set_yticks(yticks)
        plt.gca().set_yticklabels(ylabel[yticks])

    if colorbar:
        plt.colorbar()

    return results 
Example 30
Project: RLTrader   Author: notadamking   File: TradingChart.py    GNU General Public License v3.0 5 votes vote down vote up
def render(self, current_step, net_worths, benchmarks, trades, window_size=200):
        net_worth = round(net_worths[-1], 2)
        initial_net_worth = round(net_worths[0], 2)
        profit_percent = round((net_worth - initial_net_worth) / initial_net_worth * 100, 2)

        self.fig.suptitle('Net worth: $' + str(net_worth) + ' | Profit: ' + str(profit_percent) + '%')

        window_start = max(current_step - window_size, 0)
        step_range = slice(window_start, current_step + 1)
        times = self.df['Date'].values[step_range]

        self._render_net_worth(step_range, times, current_step, net_worths, benchmarks)
        self._render_price(step_range, times, current_step)
        self._render_volume(step_range, times)
        self._render_trades(step_range, trades)

        date_col = pd.to_datetime(self.df['Date'], unit='s').dt.strftime('%m/%d/%Y %H:%M')
        date_labels = date_col.values[step_range]

        self.price_ax.set_xticklabels(date_labels, rotation=45, horizontalalignment='right')

        # Hide duplicate net worth date labels
        plt.setp(self.net_worth_ax.get_xticklabels(), visible=False)

        # Necessary to view frames before they are unrendered
        plt.pause(0.001) 
Example 31
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: tools.py    MIT License 5 votes vote down vote up
def _set_ticks_props(axes, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None):
    import matplotlib.pyplot as plt

    for ax in _flatten(axes):
        if xlabelsize is not None:
            plt.setp(ax.get_xticklabels(), fontsize=xlabelsize)
        if xrot is not None:
            plt.setp(ax.get_xticklabels(), rotation=xrot)
        if ylabelsize is not None:
            plt.setp(ax.get_yticklabels(), fontsize=ylabelsize)
        if yrot is not None:
            plt.setp(ax.get_yticklabels(), rotation=yrot)
    return axes 
Example 32
Project: recruit   Author: Frank-qlu   File: _tools.py    Apache License 2.0 5 votes vote down vote up
def _set_ticks_props(axes, xlabelsize=None, xrot=None,
                     ylabelsize=None, yrot=None):
    import matplotlib.pyplot as plt

    for ax in _flatten(axes):
        if xlabelsize is not None:
            plt.setp(ax.get_xticklabels(), fontsize=xlabelsize)
        if xrot is not None:
            plt.setp(ax.get_xticklabels(), rotation=xrot)
        if ylabelsize is not None:
            plt.setp(ax.get_yticklabels(), fontsize=ylabelsize)
        if yrot is not None:
            plt.setp(ax.get_yticklabels(), rotation=yrot)
    return axes 
Example 33
Project: TF_RL   Author: Rowing0914   File: box_plot_test.py    MIT License 5 votes vote down vote up
def set_box_color(bp, color):
    plt.setp(bp['boxes'], color=color)
    plt.setp(bp['whiskers'], color=color)
    plt.setp(bp['caps'], color=color)
    plt.setp(bp['medians'], color=color) 
Example 34
Project: closed-loop-learning-in-autonomous-agents   Author: INM-6   File: plot_config.py    MIT License 5 votes vote down vote up
def set_tick_fontsize(ax, fontsize):
    plt.setp(ax.get_xticklabels(), fontsize=fontsize)
    plt.setp(ax.get_yticklabels(), fontsize=fontsize) 
Example 35
Project: dgl   Author: dmlc   File: viz.py    Apache License 2.0 5 votes vote down vote up
def att_animation(maps_array, mode, src, tgt, head_id):
    weights = [maps[mode2id[mode]][head_id] for maps in maps_array]
    fig, axes = plt.subplots(1, 2)

    def weight_animate(i):
        global colorbar
        if colorbar:
            colorbar.remove()
        plt.cla()
        axes[0].set_title('heatmap')
        axes[0].set_yticks(np.arange(len(src)))
        axes[0].set_xticks(np.arange(len(tgt)))
        axes[0].set_yticklabels(src)
        axes[0].set_xticklabels(tgt)
        plt.setp(axes[0].get_xticklabels(), rotation=45, ha="right",
                 rotation_mode="anchor")

        fig.suptitle('epoch {}'.format(i))
        weight = weights[i].transpose(-1, -2)
        heatmap = axes[0].pcolor(weight, vmin=0, vmax=1, cmap=plt.cm.Blues)
        colorbar = plt.colorbar(heatmap, ax=axes[0], fraction=0.046, pad=0.04)
        axes[0].set_aspect('equal')
        axes[1].axis("off")
        graph_att_head(src, tgt, weight, axes[1], 'graph')


    ani = animation.FuncAnimation(fig, weight_animate, frames=len(weights), interval=500, repeat_delay=2000)
    return ani 
Example 36
Project: FUTU_Stop_Loss   Author: BigtoC   File: _tools.py    MIT License 5 votes vote down vote up
def _set_ticks_props(axes, xlabelsize=None, xrot=None,
                     ylabelsize=None, yrot=None):
    import matplotlib.pyplot as plt

    for ax in _flatten(axes):
        if xlabelsize is not None:
            plt.setp(ax.get_xticklabels(), fontsize=xlabelsize)
        if xrot is not None:
            plt.setp(ax.get_xticklabels(), rotation=xrot)
        if ylabelsize is not None:
            plt.setp(ax.get_yticklabels(), fontsize=ylabelsize)
        if yrot is not None:
            plt.setp(ax.get_yticklabels(), rotation=yrot)
    return axes 
Example 37
Project: PyFluxPro   Author: OzFlux   File: pfp_plot.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_onetimeseries_right(fig,n,ThisOne,xarray,yarray,p):
    if p["ts_ax_left"][n] is not None:
        ts_ax_right = p["ts_ax_left"][n].twinx()
    else:
        rect = [p['ts_XAxOrg'],p['YAxOrg'],p['ts_XAxLen'],p['ts_YAxLen']]
        if p["ts_ax_left"][0] is not None:
            # a left axis was defined for the first graph, use it
            ts_ax_right = fig.add_axes(rect,sharex=p["ts_ax_left"][0])
        else:
            # a right axis was defined for the first graph, use it
            ts_ax_right = fig.add_axes(rect,sharex=p["ts_ax_right"][0])
        #ts_ax_right.hold(False)
        ts_ax_right.yaxis.tick_right()
        TextStr = ThisOne+'('+p['Units']+')'
        txtXLoc = p['ts_XAxOrg']+0.01
        txtYLoc = p['YAxOrg']+p['ts_YAxLen']-0.025
        plt.figtext(txtXLoc,txtYLoc,TextStr,color='b',horizontalalignment='left')
    colour = 'r'
    p["ts_ax_right"][n] = ts_ax_right
    ts_ax_right.plot(xarray,yarray,'r-')
    ts_ax_right.set_xlim(p['XAxMin'],p['XAxMax'])
    ts_ax_right.set_ylim(p['RYAxMin'],p['RYAxMax'])
    if n==0:
        ts_ax_right.set_xlabel('Date',visible=True)
    else:
        ts_ax_right.set_xlabel('',visible=False)
    TextStr = str(p['nNotM'])+' '+str(p['nMskd'])
    txtXLoc = p['ts_XAxOrg']+p['ts_XAxLen']-0.01
    txtYLoc = p['YAxOrg']+p['ts_YAxLen']-0.025
    plt.figtext(txtXLoc,txtYLoc,TextStr,color='r',horizontalalignment='right')
    if n > 0: plt.setp(ts_ax_right.get_xticklabels(),visible=False) 
Example 38
Project: pymaid   Author: schlegelp   File: cluster.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_matrix2(self, **kwargs):
        """Plot distance matrix and dendrogram using seaborn.

        Parameters
        ----------
        kwargs      dict
                    Keyword arguments to be passed to seaborn.clustermap. See
                    http://seaborn.pydata.org/generated/seaborn.clustermap.html


        Returns
        -------
        seaborn.clustermap

        """
        import matplotlib.pyplot as plt

        try:
            import seaborn as sns
        except BaseException:
            raise ImportError('Need seaborn package installed.')

        cg = sns.clustermap(self.dist_mat, row_linkage=self.linkage,
                            col_linkage=self.linkage, **kwargs)

        # Rotate labels
        plt.setp(cg.ax_heatmap.xaxis.get_majorticklabels(), rotation=90)
        plt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), rotation=0)

        # Make labels smaller
        plt.setp(cg.ax_heatmap.xaxis.get_majorticklabels(), fontsize=4)
        plt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), fontsize=4)

        # Increase padding
        cg.fig.subplots_adjust(right=.8, top=.95, bottom=.2)

        logger.info(
            'Use matplotlib.pyplot.show() to render figure.')

        return cg 
Example 39
Project: nmsat   Author: rcfduarte   File: visualization.py    GNU General Public License v2.0 5 votes vote down vote up
def set_plot_properties(pl_handle, **kwargs):
    """
    Modify and set properties of plot function
    :param pl_handle: plot handle
    :param kwargs: key-word argument, properties dictionary
    """
    pl_handle.setp(kwargs) 
Example 40
Project: pyDataView   Author: edwardsmith999   File: plot.py    GNU General Public License v3.0 5 votes vote down vote up
def update_plot_many(self, axs, datas):
        for line, ax, data in zip(self.lines, axs, datas):
            plt.setp(line, xdata=ax, ydata=data)
        self.canvas.draw() 
Example 41
Project: pyDataView   Author: edwardsmith999   File: plot.py    GNU General Public License v3.0 5 votes vote down vote up
def update_plot(self, ax, data):
        plt.setp(self.lines, xdata=ax, ydata=data)
        self.canvas.draw() 
Example 42
Project: DeepDIVA   Author: DIVA-DIA   File: dataset_bidimensional.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _visualize_distribution(train, val, test, save_path, marker_size=1):
    """
    This routine creates a PDF with three images for train, val and test respectively where
    each image is a visual representation of the split distribution with class colors.

    Parameters
    ----------
    train, val, test : ndarray[float] of size (n,3)
        The three splits. Each row is (x,y,label)
    save_path : String
        Path where to save the PDF
    marker_size : float
        Size of the marker representing each datapoint. For big dataset make this small

    Returns
    -------
        None
    """
    fig, axs = plt.subplots(ncols=3, sharex='all', sharey='all')
    plt.setp(axs.flat, aspect=1.0, adjustable='box-forced')
    axs[0].scatter(train[:, 0], train[:, 1], c=train[:, 2], s=marker_size, cmap=plt.get_cmap('Set1'))
    axs[0].set_title('train')
    axs[1].scatter(val[:, 0], val[:, 1], c=val[:, 2], s=marker_size, cmap=plt.get_cmap('Set1'))
    axs[1].set_title('val')
    axs[2].scatter(test[:, 0], test[:, 1], c=test[:, 2], s=marker_size, cmap=plt.get_cmap('Set1'))
    axs[2].set_title('test')
    fig.canvas.draw()
    fig.savefig(save_path)
    fig.clf()
    plt.close() 
Example 43
Project: spatial_patterns   Author: sim-web   File: plotting.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_time_evolution(self, observable, t_start=0, t_end=None,
                            method='langston', spacing=None, from_file=True,
                            data=False, n_cumulative=1, vlines=None):
        """Plots time evolution of given observable

        Parameters
        ----------
        observable : string
            'grid_score', 'grid_spacing'
        data : bool
            If True the data is taken from 'computed'. It needs to be created
            there first using add_computed.py in a separate step.
        """
        for psp in self.psps:
            self.set_params_rawdata_computed(psp, set_sim_params=True)
            if t_end == None:
                t_end = self.simulation_time
            time_increment = self.every_nth_step_weights * self.dt
            time = np.arange(t_start, t_end+time_increment, time_increment)
            observable_list = []
            if observable == 'grid_score':
                for t in time:
                    observable_list.append(self.get_grid_score(t, spacing,
                                                    method, from_file, data))
                observable_list = self.computed['grid_score'][method][str(n_cumulative)]
                plt.ylim([-0.6, 1.4])
                plt.hlines([0.0], t_start, t_end,
                                color='black',linestyle='dashed', lw=2)
                plt.ylabel('Grid score')

            plt.xlabel('Time [hrs]')
            if vlines:
                for x in vlines:
                    plt.axvline(x)
            plt.plot(time, observable_list, lw=2, marker='o', color='black')
            ax = plt.gca()
            xticks = np.array([t_start, t_end/2, t_end])
            plt.setp(ax,
                     xticks=xticks,
                     xticklabels=xticks / (3e3*60)) 
Example 44
Project: spatial_patterns   Author: sim-web   File: figures.py    GNU General Public License v3.0 5 votes vote down vote up
def two_dimensional_input_tuning():
	x, y = np.mgrid[-1:1:.01, -1:1:.01]
	pos = np.dstack((x, y))
	gaussian = scipy.stats.multivariate_normal([0., 0.], np.power([0.05, 0.1], 2))
	vanishing_value = 1e-1
	# fields = field(positions, location, sigma_exc).reshape((n_x, n_x))
	cm = mpl.cm.Reds
	my_masked_array = np.ma.masked_less(gaussian.pdf(pos), vanishing_value)
	plt.contourf(x, y, my_masked_array, cmap=cm)
	ax = plt.gca()
	# ax.set_aspect('equal')
	plt.setp(ax, aspect='equal', xticks=[], yticks=[])
	plt.axis('off')


# def plot_grid_score_histogram(grid_scores, start_frame=0, end_frame=-1):
# 	"""
# 	Grid score histogram
#
# 	Parameters
# 	----------
#
#
# 	Returns
# 	-------
# 	"""
# 	# date_dir = '2016-04-01-10h24m43s_600_minutes_very_fast_learning'
# 	# tables = get_tables(date_dir=date_dir)
# 	# plot = plotting.Plot(tables=tables, psps=None)
# 	# grid_score = plot.tables.get_computed(None)['grid_score']
# 	# print grid_score['Weber']['1'].shape
# 	hist_kwargs = {'alpha': 0.5, 'bins': 20}
# 	grid_scores = grid_score['Weber']['1'][:, end_frame]
# 	grid_scores = grid_scores[~np.isnan(grid_scores)]
# 	plt.hist(grid_scores, **hist_kwargs)
# 	print grid_scores 
Example 45
Project: spatial_patterns   Author: sim-web   File: figures.py    GNU General Public License v3.0 5 votes vote down vote up
def _grid_score_histogram(
		grid_spec, plot_class, grid_scores, seed=0, end_frame=-1, dummy=False,
		grid_score_marker=False, show_number_of_simulations=False,
		leftmost_histogram=False, show_initial_fraction=True,
		labelpad=0):
	ax = plt.gcf().add_subplot(grid_spec)
	if not dummy:
		plot_class.plot_grid_score_histogram(grid_scores, end_frame=end_frame,
								show_initial_fraction=show_initial_fraction)
		if grid_score_marker:
			init_grid_score = grid_scores[seed, :][0]
			final_grid_score = grid_scores[seed, :][-1]
			colors = {'init': color_cycle_blue4[2], 'final': color_cycle_blue4[0]}
			grid_score_arrow(init_grid_score, color=colors['init'])
			grid_score_arrow(final_grid_score, color=colors['final'])
		if show_number_of_simulations:
			### WARNING: shows on how many simulations the histogram is based on
			plt.text(0.5, 0.5, str(len(grid_scores)),
					 horizontalalignment='center',
					 verticalalignment='center',
					 transform=plt.gca().transAxes, color='red')
		general_utils.plotting.simpleaxis(ax)
	else:
		dummy_plot()
	ylabel = '# Cells ' if leftmost_histogram else ''
	plt.setp(ax,
			 xlabel='Grid score')
	plt.ylabel(ylabel, labelpad=labelpad)
	return ax 
Example 46
Project: spatial_patterns   Author: sim-web   File: figures.py    GNU General Public License v3.0 5 votes vote down vote up
def simple_polar(self, ax):
		"""
		Minimalistic axis for polar plots
		"""
		plt.setp(ax, yticks=[])
		ax.spines['polar'].set_visible(False)
		thetaticks = np.arange(0,360,90)
		ax.set_thetagrids(thetaticks, []) 
Example 47
Project: spatial_patterns   Author: sim-web   File: figures.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_xlabel_and_sizebar(self, plot_sizebar=False):
		"""
		Used to add the size bar label and the size bar to rate maps.

		Usable in Figure 2 (grids) and Figure 4 (cell types).
		This plots a sizebar inside the contour plots.
		In order to get it under the figure, you need to create two
		plots, one with sizebars, and one without. The one with sizebars
		your mask and remove leftover with white boxes.
		This is a hack, but it's better than adjusting the sizebars
		manually.

		Parameters
		----------
		plot_sizebar : bool
			If False, only the xlabel is plotted.
			If True, a sizebar is plotted inside the rate map
			or the correlogram or the input tuning
		"""
		r = 0.5
		ax = plt.gca()
		# ax.spines['right'].set_color('none')
		# ax.spines['top'].set_color('none')
		# ax.spines['left'].set_color('none')
		# ax.spines['bottom'].set_color('none')
		plt.setp(ax, xticks=[], yticks=[], xlim=[-r, r], ylim=[-r, r],
				 aspect='equal')
		if plot_sizebar:
			plt.plot([-r, r], [-r, -r], color='black', lw=5)
		ax.set_xlabel('1m') 
Example 48
Project: py-bgo   Author: PredictiveScienceLab   File: _core.py    MIT License 5 votes vote down vote up
def plot_summary(f, X_design, model, prefix, G, Gamma_name):
    """
    Plot a summary of the current iteration.
    """
    import matplotlib.pyplot as plt
    import seaborn as sns
    X = model.X
    y = model.Y
    m_s, k_s = model.predict(X_design, full_cov=True)
    m_05, m_95 = model.predict_quantiles(X_design)
    fig, ax1 = plt.subplots()
    yt = np.array([f(X_design[i, :]) for i in xrange(X_design.shape[0])])
    ax1.plot(X_design, yt, linewidth=2, color=sns.color_palette()[2])
    ax1.plot(X, y, 'x', linewidth=2, markersize=10, markeredgewidth=2,
             color='black')
    ax1.plot(X_design, m_s, '--', linewidth=2, color=sns.color_palette()[0])
    ax1.fill_between(X_design.flatten(), m_05.flatten(), m_95.flatten(),
                     color=sns.color_palette()[0], alpha=0.25)
    i = np.argmax(G)
    ax1.plot(X_design[i], yt[i], 'o', markersize=10, markeredgewidth=2,
             color=sns.color_palette()[1])
    ax1.set_ylabel('$f(x)$', fontsize=16)
    ax1.set_xlabel('$x$', fontsize=16)
    ax2 = ax1.twinx()
    ax2.plot(X_design, G, ':', linewidth=2, color=sns.color_palette()[1])
    ax2.set_ylabel('$\\operatorname{%s}(x)$' % Gamma_name, fontsize=16, color=sns.color_palette()[1])
    ax2.set_ylim([0., 2.])
    plt.setp(ax2.get_yticklabels(), color=sns.color_palette()[1])
    png_file = prefix + '.png'
    print '+ writing:', png_file
    fig.savefig(png_file)
    plt.close(fig) 
Example 49
Project: py-bgo   Author: PredictiveScienceLab   File: _core.py    MIT License 5 votes vote down vote up
def plot_summary_no_feval(f, X_design, model, prefix, G, Gamma_name):
    """
    Plot a summary of the current iteration.
    """
    import matplotlib.pyplot as plt
    import seaborn as sns
    X = model.X
    y = model.Y
    m_s, k_s = model.predict(X_design, full_cov=True)
    m_05, m_95 = model.predict_quantiles(X_design)
    fig, ax1 = plt.subplots()
    ax1.plot(X, y, 'x', linewidth=2, markersize=10, markeredgewidth=2,
             color='black')
    ax1.plot(X_design, m_s, '--', linewidth=2, color=sns.color_palette()[0])
    ax1.fill_between(X_design.flatten(), m_05.flatten(), m_95.flatten(),
                     color=sns.color_palette()[0], alpha=0.25)
    i = np.argmax(G)
    ax1.set_ylabel('$f(x)$', fontsize=16)
    ax1.set_xlabel('$x$', fontsize=16)
    ax2 = ax1.twinx()
    ax2.plot(X_design, G, ':', linewidth=2, color=sns.color_palette()[1])
    ax2.set_ylabel('$\\operatorname{%s}(x)$' % Gamma_name, fontsize=16, color=sns.color_palette()[1])
    ax2.set_ylim([0., 2.])
    plt.setp(ax2.get_yticklabels(), color=sns.color_palette()[1])
    png_file = prefix + '.png'
    print '+ writing:', png_file
    fig.savefig(png_file)
    plt.close(fig) 
Example 50
Project: py-bgo   Author: PredictiveScienceLab   File: _global_optimizer.py    MIT License 5 votes vote down vote up
def plot_opt_status_1d(self, it):
        if self.verbose:
            print '\t\t> plotting the optimization status'
        import matplotlib.pyplot as plt
        import seaborn as sns
        Y_d = self.denoised_posterior_samples
        fig, ax1 = self.new_fig_func()
        ax2 = ax1.twinx()
        p_025 = np.percentile(Y_d, 2.5, axis=0)
        p_500 = np.percentile(Y_d, 50, axis=0)
        p_975 = np.percentile(Y_d, 97.5, axis=0)
        ax1.fill_between(self.X_design.flatten(), p_025, p_975,
                         color=colorAlpha_to_rgb(sns.color_palette()[0], 0.25),
                         label='95\% error')
        ax1.plot(self.X_design, p_500, color=sns.color_palette()[0],
                      label='Pred. mean')
        ax1.plot(self.X[:-1, :], self.Y[:-1],
                 'kx', markersize=10, markeredgewidth=2,
                 label='Observations')
        if self.true_func is not None:
            ax1.plot(self.X_design, self.Y_true,
                     ':', color=sns.color_palette()[2])
        ax1.plot(self.X[-1, 0], self.Y[-1], 'o',
                 markersize=10, markeredgewidth=2,
                 color=sns.color_palette()[1])
        ax2.plot(self.X_design, self.ei / self.ei_values[0],
                 '--', color=sns.color_palette()[3],
                      label='Exp. improvement')
        ax2.set_ylim(0, 1.5)
        plt.setp(ax2.get_yticklabels(), color=sns.color_palette()[3])
        figname = self._fig_name('state', it)
        if self.verbose:
            print '\t\t> writing:', figname
        fig.savefig(figname)
        plt.close(fig)