Example #1
0
    def plot_contour(self, x, y, z, position = 111, ax_label = False,\
            contour_label = True, label = 'saturation []',\
            title = 'saturation', xlab = 'x [m]', ylab = 'z [m]',\
            section = False):
        """ takes in numpy arrays of same shape
        """
        ax_c = self.fig.add_subplot(position)
        plt.tick_params(which='major', length=3, color = 'w')
        if label == 'saturation []':
            n_levels = 8
            v = np.linspace(0., 0.8, num = n_levels)
            CS = ax_c.contourf(x,y,z,v)
        else:
            CS = ax_c.contourf(x,y,z)
        if contour_label == True:
            self.fig.subplots_adjust(right=0.84)
            cb_axes = self.fig.add_axes([0.85, 0.15, 0.05, 0.7])
            plt.tick_params(which='major', length=3, color = 'k')
            self.fig.colorbar(CS, cax = cb_axes, format = '%.2f')
            #CB = plt.colorbar(CS, shrink = 1.0, pad=0.02, fraction = 0.07,\
                    #extend = 'both', format='%.2f')
        if ax_label != True:
            ax_c.set_yticklabels([])
        if section == True:
            ax_c.xaxis.set_ticks(np.arange(0,6000,2500))
        else:
            ax_c.xaxis.set_ticks(np.arange(0,3500,1000))
            ax_c.set_xticklabels([])


        #ax_c.set_xlabel(xlab)
        #ax_c.set_aspect('equal')
        ax_c.set_title(title)
        return 0
Example #2
0
def plot_scenario(strategies, names, scenario_id=1):
    probabilities = get_scenario(scenario_id)

    plt.figure(figsize=(6, 4.5))

    ax = plt.subplot(111)
    ax.spines["top"].set_visible(False)
    ax.spines["bottom"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.spines["left"].set_visible(False)

    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

    plt.yticks(fontsize=14)
    plt.xticks(fontsize=14)
    plt.xlim((0, 1300))

    # Remove the tick marks; they are unnecessary with the tick lines we just plotted.
    plt.tick_params(axis="both", which="both", bottom="on", top="off",
                    labelbottom="on", left="off", right="off", labelleft="on")

    for rank, (strategy, name) in enumerate(zip(strategies, names)):
        plot_strategy(probabilities, strategy, name, rank)

    plt.title("Bandits: " + str(probabilities), fontweight='bold')
    plt.xlabel('Number of Trials', fontsize=14)
    plt.ylabel('Cumulative Regret', fontsize=14)
    plt.legend(names)
    plt.show()
Example #3
0
def draw_digit(data):
    size = int(len(data) ** 0.5)
    Z = data.reshape(size, size)  # convert from vector to matrix
    plt.imshow(Z, interpolation="None")
    plt.gray()
    plt.tick_params(labelbottom="off")
    plt.tick_params(labelleft="off")
def plot_2D_offsets(df, stat_key, prefices=["Delta_x_", "Delta_y_"],
                    suffices=["_x", "_y"], prefix_bool=1):
    for i, key in enumerate(stat_key) :
        plt.axes().set_aspect('equal')
        if prefix_bool:
            fixed_keys = [prefices[0] + key, prefices[1] + key]
        else:
            fixed_keys = [key + suffices[0], key + suffices[1]]

        plt.plot(
            np.array(df[fixed_keys[0]]),
            np.array(df[fixed_keys[1]]), 'b.', alpha=0.05
            )
        biweight_loc = (
            biweight_location(df[fixed_keys[0]]),
            biweight_location(df[fixed_keys[1]]))

        # The red cross is the biweight location along each dimension
        plt.plot(biweight_loc[0], biweight_loc[1],
             'rx', mew=2.)
        plt.tick_params(labeltop='off', labelright='off')
        plt.axes().yaxis.set_ticks_position('left')
        plt.axes().xaxis.set_ticks_position('bottom')
        plt.xlim(-300, 300)
        plt.ylim(-300, 300)
        plt.title(key + ', biweight_loc = {0:.2f}, {1:.2f}'.format(
            *biweight_loc))

        plt.show()
        plt.clf()
 def __init__(self):
     # 図を描く大きさと、図の変数名を宣言
     fig = plt.figure(figsize=(5, 5))
     ax = plt.gca()
      
     # 赤い壁を描く
     plt.plot([1, 1], [0, 1], color='red', linewidth=2)
     plt.plot([1, 2], [2, 2], color='red', linewidth=2)
     plt.plot([2, 2], [2, 1], color='red', linewidth=2)
     plt.plot([2, 3], [1, 1], color='red', linewidth=2)
      
     # 状態を示す文字S0~S8を描く
     plt.text(0.5, 2.5, 'S0', size=14, ha='center')
     plt.text(1.5, 2.5, 'S1', size=14, ha='center')
     plt.text(2.5, 2.5, 'S2', size=14, ha='center')
     plt.text(0.5, 1.5, 'S3', size=14, ha='center')
     plt.text(1.5, 1.5, 'S4', size=14, ha='center')
     plt.text(2.5, 1.5, 'S5', size=14, ha='center')
     plt.text(0.5, 0.5, 'S6', size=14, ha='center')
     plt.text(1.5, 0.5, 'S7', size=14, ha='center')
     plt.text(2.5, 0.5, 'S8', size=14, ha='center')
     plt.text(0.5, 2.3, 'START', ha='center')
     plt.text(2.5, 0.3, 'GOAL', ha='center')
      
     # 描画範囲の設定と目盛りを消す設定
     ax.set_xlim(0, 3)
     ax.set_ylim(0, 3)
     plt.tick_params(axis='both', which='both', bottom=False, top=False,
                     labelbottom=False, right=False, left=False, labelleft=False)
      
     self.fig = fig
     self.ax = ax
Example #6
0
def plot_obs_expc_new(obs, expc, expc_upper, expc_lower, analysis, log, ax = None):
    """Modified version of obs-expc plot suggested by R2. The points are separated by whether their CIs are above, below, 
    
    or overlapping the empirical value
    Input: 
    obs - list of observed values
    expc_mean - list of mean simulated values for the corresponding observed values
    expc_upper - list of the 97.5% quantile of the simulated vlaues
    expc_lower - list of the 2.5% quantile of the simulated values
    analysis - whether it is patitions or compositions
    log - whether the y axis is to be transformed. If True, expc/obs is plotted. If Flase, expc - obs is plotted.
    ax - whether the plot is generated on a given figure, or a new plot object is to be created
    
    """
    obs, expc, expc_upper, expc_lower = list(obs), list(expc), list(expc_upper), list(expc_lower)
    if not ax:
        fig = plt.figure(figsize = (3.5, 3.5))
        ax = plt.subplot(111)
    
    ind_above = [i for i in range(len(obs)) if expc_lower[i] > obs[i]]
    ind_below = [i for i in range(len(obs)) if expc_upper[i] < obs[i]]
    ind_overlap = [i for i in range(len(obs)) if expc_lower[i] <= obs[i] <= expc_upper[i]]
    
    if log:
        expc_standardize = [expc[i] / obs[i] for i in range(len(obs))]
        expc_upper_standardize = [expc_upper[i] / obs[i] for i in range(len(obs))]
        expc_lower_standardize = [expc_lower[i] / obs[i] for i in range(len(obs))]
        axis_min = 0.9 * min([expc_lower_standardize[i] for i in range(len(expc_lower_standardize)) if expc_lower_standardize[i] != 0])
        axis_max = 1.5 * max(expc_upper_standardize)
    else:
        expc_standardize = [expc[i] - obs[i] for i in range(len(obs))]
        expc_upper_standardize = [expc_upper[i] - obs[i] for i in range(len(obs))]
        expc_lower_standardize = [expc_lower[i] - obs[i] for i in range(len(obs))]
        axis_min = 1.1 * min(expc_lower_standardize)
        axis_max = 1.1 * max(expc_upper_standardize)
   
    if analysis == 'partition': col = '#228B22'
    else: col = '#CD69C9'
    ind_full = [] 
    for index in [ind_below, ind_overlap, ind_above]:
        expc_standardize_ind = [expc_standardize[i] for i in index]
        sort_ind_ind = sorted(range(len(expc_standardize_ind)), key = lambda i: expc_standardize_ind[i])
        sorted_index = [index[i] for i in sort_ind_ind]
        ind_full.extend(sorted_index)

    xaxis_max = len(ind_full)
    for i, ind in enumerate(ind_full):
        plt.plot([i, i],[expc_lower_standardize[ind], expc_upper_standardize[ind]], '-', c = col, linewidth = 0.4)
    plt.scatter(range(len(ind_full)), [expc_standardize[i] for i in ind_full], c = col,  edgecolors='none', s = 8)    
    if log: 
        plt.plot([0, xaxis_max + 1], [1, 1], 'k-', linewidth = 1.5)
        ax.set_yscale('log')
    else: plt.plot([0, xaxis_max + 1], [0, 0], 'k-', linewidth = 1.5)
    plt.plot([len(ind_below) - 0.5, len(ind_below) - 0.5], [axis_min, axis_max], 'k--')
    plt.plot([len(ind_below) + len(ind_overlap) - 0.5, len(ind_below) + len(ind_overlap) - 0.5], [axis_min, axis_max], 'k--')
    plt.xlim(0, xaxis_max)
    plt.ylim(axis_min, axis_max)
    plt.tick_params(axis = 'y', which = 'major', labelsize = 8, labelleft = 'on')
    plt.tick_params(axis = 'x', which = 'major', top = 'off', bottom = 'off', labelbottom = 'off')
    return ax
Example #7
0
def plot_images(data_list, data_shape="auto", fig_shape="auto"):
    """
    plotting data on current plt object.
    In default,data_shape and fig_shape are auto.
    It means considered the data as a sqare structure.
    """
    n_data = len(data_list)
    if data_shape == "auto":
        sqr = int(n_data ** 0.5)
        if sqr * sqr != n_data:
            data_shape = (sqr + 1, sqr + 1)
        else:
            data_shape = (sqr, sqr)
    plt.figure(figsize=data_shape)

    for i, data in enumerate(data_list):
        plt.subplot(data_shape[0], data_shape[1], i + 1)
        plt.gray()
        if fig_shape == "auto":
            fig_size = int(len(data) ** 0.5)
            if fig_size ** 2 != len(data):
                fig_shape = (fig_size + 1, fig_size + 1)
            else:
                fig_shape = (fig_size, fig_size)
        Z = data.reshape(fig_shape[0], fig_shape[1])
        plt.imshow(Z, interpolation="nearest")
        plt.tick_params(labelleft="off", labelbottom="off")
        plt.tick_params(axis="both", which="both", left="off", bottom="off", right="off", top="off")
        plt.subplots_adjust(hspace=0.05)
        plt.subplots_adjust(wspace=0.05)
def PlotIOCurve(stRaster, rasterKey, figPath=[]):
	""" Plot the IO curves for the spikes in stRaster.        
	:param stRaster: dict of pandas.DataFrame of spike times for each cycle, for each intensity 
	:type stRaster: dict of pandas.DataFrame
	:param rasterKey: Raster key with intensity in dB following '_'
	:type rasterKey: str
	:param figPath: Directory location for plots to be saved
	:type figPath: str
	:returns: tuningCurves: pandas.DataFrame with frequency, intensity, response rate and standard deviation 
	"""
	tuning = []
	sortedKeys = sorted(stRaster.keys())
	for traceKey in sortedKeys:
		spl = int(traceKey.split('_')[-1])
		raster = stRaster[traceKey]
		res = ResponseStats( raster )
		tuning.append({'intensity': spl, 'response': res[0], 'responseSTD': res[1]})
	tuningCurves = pd.DataFrame(tuning)
	testNum = int(rasterKey.split('_')[-1])
	tuningCurves.plot(x='intensity', y='response', yerr='responseSTD', capthick=1, label='test '+str(testNum))
	plt.legend(loc='upper left', fontsize=12, frameon=True)
	sns.despine()
	plt.grid(False)
	plt.xlabel('Intensity (dB)', size=14)
	plt.ylabel('Response Rate (Hz)', size=14)
	plt.tick_params(axis='both', which='major', labelsize=14)
	title = rasterKey.split('_')[0]+'_'+rasterKey.split('_')[1]+'_'+rasterKey.split('_')[2]
	plt.title(title, size=14)
	if len(figPath)>0: 
		plt.savefig(figPath + 'ioCurves_' + title +'.png')
	return tuningCurves
def test_rotated_labels_parameters_no_ticks():
    fig, ax = __plot()

    ax.xaxis.set_ticks([])

    plt.tick_params(axis='x',
                    which='both',
                    bottom='off',
                    top='off')
    plt.tick_params(axis='y',
                    which='both',
                    left='off',
                    right='off')

    # convert to tikz file
    _, tmp_base = tempfile.mkstemp()
    tikz_file = tmp_base + '_tikz.tex'

    matplotlib2tikz.save(
        tikz_file,
        figurewidth='7.5cm'
        )

    # close figure
    plt.close(fig)

    # delete file
    os.unlink(tikz_file)
    return
Example #10
0
def valueChartList(inputlist,path):
    seen_values = Counter()

    for dict in inputlist:
        seen_values += Counter(dict['location-value-pair'].values())

    seen_values = seen_values.most_common()[:25]
    seen_values_pct = map(itemgetter(1), tupleCounts2Percents(seen_values))
    seen_values_pct = ['{:.1%}'.format(item)for item in seen_values_pct]

    plt.figure()
    numberchart = plt.bar(range(len(seen_values)), map(itemgetter(1), seen_values), width=0.9,alpha=0.6)
    plt.xticks(range(len(seen_values)), map(itemgetter(0), seen_values),ha='left')

    plt.ylabel('Occurrences')

    plot_margin = 1.15
    x0, x1, y0, y1 = plt.axis()
    plt.axis((x0,
              x1,
              y0,
              y1*plot_margin))

    plt.tick_params(axis='both', which='major', labelsize=8)
    plt.tick_params(axis='both', which='minor', labelsize=8)
    plt.tight_layout()

    autolabel(numberchart,seen_values_pct)

    plt.savefig(path)
    plt.clf()
Example #11
0
def chartProperties(counter,path):

    seen_properties = sorted(counter, key=lambda x: x[1],reverse=True)
    seen_values_pct = map(itemgetter(1), tupleCounts2Percents(seen_properties))
    seen_values_pct = ['{:.1%}'.format(item)for item in seen_values_pct]

    plt.figure()

    numberchart = plt.bar(range(len(seen_properties)), map(itemgetter(1), seen_properties), width=0.9,alpha=0.6)
    plt.xticks(range(len(seen_properties)), map(itemgetter(0), seen_properties),rotation=90,ha='left')

    plt.ylabel('Occurrences')

    plot_margin = 1.15
    x0, x1, y0, y1 = plt.axis()
    plt.axis((x0,
              x1,
              y0,
              y1*plot_margin))

    plt.tick_params(axis='both', which='major', labelsize=8)
    plt.tick_params(axis='both', which='minor', labelsize=8)
    plt.tight_layout()

    autolabel(numberchart,seen_values_pct)

    plt.savefig(path)
    plt.clf()
Example #12
0
def makeSigBkg(all_outputs, targets, label,
              dir='/afs/cern.ch/user/j/jpavezse/systematics',model_g='mlp',
              print_pdf=False,legends=None, title=''):
  '''
  make plots for ROC curve of classifier and
  test data.
  '''
  tprs = []
  fnrs = []
  aucs = []
  thresholds = np.linspace(0,1.0,150) 
  fig = plt.figure()
  for k,(outputs,target) in enumerate(zip(all_outputs,targets)):
    fnrs.append(np.array([float(np.sum((outputs > tr) * (target == 0)))/float(np.sum(target == 0)) for tr in thresholds]))
    fnrs[-1] = fnrs[-1].ravel()
    tprs.append(np.array([float(np.sum((outputs < tr) * (target == 1)))/float(np.sum(target == 1)) for tr in thresholds]))
    tprs[-1] = tprs[-1].ravel()
    aucs.append(auc(tprs[-1],fnrs[-1]))
    plt.plot(tprs[-1], fnrs[-1], label='ROC {0} (area = {1:.2f})'.format(
       legends[k],aucs[-1]))
  plt.xlim([0.0, 1.0])
  plt.ylim([0.0, 1.05])
  plt.xlabel('Signal Efficiency',fontsize=11)
  plt.ylabel('Background Rejection',fontsize=11)
  plt.tick_params(axis='both', labelsize=10)
  plt.title('{0}'.format(title))
  plt.legend(loc="lower left",frameon=False, fontsize=11)
  #np.savetxt('{0}/plots/{1}/results/{2}.txt'.format(dir,model_g,label),np.column_stack((tpr,fnr)))
  plt.savefig('{0}/plots/{1}/{2}.png'.format(dir,model_g,label))
  if print_pdf == True:
    plt.savefig('{0}/plots/{1}/{2}.pdf'.format(dir,model_g,label))
  plt.close(fig)
  plt.clf()
Example #13
0
def plot_forces_violinplots(experiment):
    ensemble = experiment.observations.kinematics
    ensembleF = ensemble.loc[
        (ensemble['position_x'] > 0.25) & (ensemble['position_x'] < 0.95),
        ['totalF_x', 'totalF_y', 'totalF_z',
         'randomF_x', 'randomF_y', 'randomF_z',
         'upwindF_x',
         'wallRepulsiveF_x', 'wallRepulsiveF_y', 'wallRepulsiveF_z',
         'stimF_x', 'stimF_y', 'stimF_z']] #== Nans
    # plot Forces
    #    f, axes = plt.subplots(2, 2, figsize=(9, 9), sharex=True, sharey=True)
    ##    forcefig = plt.figure(5, figsize=(9, 8))
    ##    gs2 = gridspec.GridSpec(2, 2)
    ##    Faxs = [fig.add_subplot(ss) for ss in gs2]
    forcefig = plt.figure()
    #    Faxs1 = forcefig.add_subplot(211)
    #    Faxs2 = forcefig.add_subplot(212)
    sns.violinplot(ensembleF, lw=3, alpha=0.7, palette="Set2")
    #    tF = sns.jointplot('totalF_x', 'totalF_y', ensemble, kind="hex", size=10)
    plt.suptitle("Force distributions")
    #    plt.xticks(range(4,((len(alignments.keys())+1)*4),4), [i[1] for i in medians_sgc], rotation=90, fontsize = 4)
    plt.tick_params(axis='x', pad=4)
    plt.xticks(rotation=40)
    #    remove_border()
    plt.tight_layout(pad=1.8)
    plt.ylabel("Force magnitude distribution (newtons)")

    fileappend, path, agent = get_agent_info(experiment.agent)

    plt.savefig(os.path.join(path, "Force Distributions" + fileappend + FIG_FORMAT))
    plt.show()
Example #14
0
def plot_2hist(false_values, true_values, hist_bins=None, labels=None, hist_title=None ):
    
    if not hist_bins:
        try:
            hist_bins = ( min( min(false_values), min(true_values)), max( max(false_values), max(true_values)), 50 )
        except ValueError:
            hist_bins = (0, 1, 2)
        
    bins = numpy.linspace( hist_bins[0], hist_bins[1], hist_bins[2] )
    
    if not labels:
        label0 = namestr(false_values)
        label1 = namestr(true_values)
    else:
        label0 = labels[0]
        label1 = labels[1]
    
    pyplot.hist([ [false_values], [true_values] ], bins, color=('red', 'blue'), label=(label0,label1), normed=True )
    
    pyplot.legend(loc='upper right', fontsize=18)
    pyplot.title( hist_title,  fontsize=24)
    
    pyplot.tick_params(axis='x', labelsize=16)
    pyplot.tick_params(axis='y', labelsize=16)

    return 1
Example #15
0
def plot_first_k_numbers(X,k):
    m = X.shape[0]
    k = min(m,k)
    j = int(round(k / 10.0))

    fig, ax = plt.subplots(j,10)

    for i in range(k):
        w=X[i,:]

        w=w.reshape(28,28)
        ax[i/10, i%10].imshow(w, cmap=plt.cm.gist_yarg, interpolation='nearest', aspect='equal')
        ax[i/10, i%10].axis('off')

    plt.tick_params(
        axis='x',          # changes apply to the x-axis
        which='both',      # both major and minor ticks are affected
        bottom='off',      # ticks along the bottom edge are off
        top='off',         # ticks along the top edge are off
        labelbottom='off')
    plt.tick_params(
        axis='y',          # changes apply to the x-axis
        which='both',      # both major and minor ticks are affected
        left='off',
        right='off',    # ticks along the top edge are off
        labelleft='off')

    fig.show()
Example #16
0
def plot_currents(gex,ginh , xlabel = 'Time (s)',ylabel='ylabel',title='Title',color='r',
                  filename='currents',
                  size=(10, 5),fontsize= 10,lw=2,marker='',ylims=(-5,5),xticks=[],yticks=[]):
    fig = plt.figure()
    ax = plt.gca()
    fig.set_size_inches(size)
    plt.plot(gex,linewidth = lw, marker=marker, color ='darkgreen' )
    plt.plot(-1 * ginh,linewidth = lw,marker=marker, color ='darkred' )
    if not ARTISTIC_PLOT:
        plt.xlabel(xlabel,fontsize=fontsize)
    plt.ylabel(ylabel,fontsize=fontsize)
    if SHOW_TITLE:
        plt.title(title, fontsize=fontsize)
    plt.tick_params(labelsize=fontsize)
    ax.spines['top'].set_color('none')
    ax.spines['right'].set_color('none')
    plt.gcf().subplots_adjust(bottom=.4,left=.2)
    plt.xlim([0,10000])
    plt.ylim(ylims)
    ax.yaxis.set_ticks_position('left')
    ax.xaxis.set_ticks_position('bottom')
    if len (xticks ) > 0:
        plt.xticks(xticks,xlabels)
    if len (yticks ) > 0:
        plt.yticks(yticks)
    if ARTISTIC_PLOT:
        ax.spines['bottom'].set_color('none')
        plt.xticks([])
    if SAVE_PLOTS:
        plt.savefig('results/' + filename+'.eps')
        plt.savefig('results/' + filename+'.png')
Example #17
0
def plot_nice(data, xlabel = 'Time (s)',ylabel='ylabel',title='Title',color='b', dims = 1, filename='nice',
              size=(10,5), fontsize= 10,lw=2,marker='',xticks=[],yticks=[]):
    fig = plt.figure()
    ax = plt.gca()
    fig.set_size_inches(size)
    if dims == 1:
        plt.plot(data,linewidth = lw, color =color ,marker=marker)
    else:
        plt.plot(data[0],data[1], linewidth = lw, color=color)
    if not ARTISTIC_PLOT:
        plt.xlabel(xlabel,fontsize=fontsize)
    plt.ylabel(ylabel,fontsize=fontsize)
    if SHOW_TITLE:
        plt.title(title,fontsize=fontsize)
    plt.tick_params(labelsize=fontsize)
    ax.spines['top'].set_color('none')
    ax.spines['right'].set_color('none')
    ax.yaxis.set_ticks_position('left')
    ax.xaxis.set_ticks_position('bottom')
    plt.gcf().subplots_adjust(bottom=.4,left=.2)

    if ARTISTIC_PLOT:
        ax.spines['bottom'].set_color('none')
    if len (xticks ) > 0 and not ARTISTIC_PLOT:
        plt.xticks(xticks,xlabels)
    #if len (yticks ) > 0:
    plt.yticks(yticks)
    if ARTISTIC_PLOT:
        ax.spines['bottom'].set_color('none')
        plt.xticks([])
    if SAVE_PLOTS:
        plt.savefig('results/' + filename+'.eps')
        plt.savefig('results/' + filename+'.png')
Example #18
0
def qnqc():
    print("Hello World")
    n = args.number
    for i in range(n):
        name = str(i) + "/qnqc"
        data = pd.read_table(name, header=None, names=["qn", "qc"])
        ax = plt.subplot(4, 5, i + 1)
        plt.tick_params(
            axis='x',
            which='both',
            bottom='off',
            top='off',
            labelbottom='off'
        )
        plt.tick_params(
            axis='y',
            which='both',
            right='off',
        )
        data.plot(ax=ax, legend=False, ylim=(0, 1))
    # print(data)
    # data.plot()
    # plt.plot(data[1])
    # plt.show()
    # ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
    # df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
    # df = df.cumsum()
    # fig = plt.figure()
    # plt.subplot(4, 4, 13)
    # plt.plot(range(12))
    plt.suptitle('Red is Qn, Blue is Qc')
    fig = plt.gcf()
    output = args.outname
    fig.savefig(output)
    os.system("open " + output)
Example #19
0
def plot_fft(spectrum, title, dry = False, custom = None):
    '''
    Plots a spectrogram as obtained in the above function. These conventions
    are mostly lifted straight from the matplotlib api. 
    '''
    n_bins, n_windows = spectrum.shape
    x_axis = np.linspace(0, (n_bins - 1) * n_windows / 44100., n_windows)
    y_axis = np.linspace(0, 22050., n_bins)
    X, Y = np.meshgrid(x_axis, y_axis)
    plt.close('all')
    plt.figure(figsize = (20, 13))
    ax = plt.gca()
    ax.set_yscale('symlog')
    im = ax.pcolormesh(X, Y, spectrum, cmap = inferno)
    plt.title(title)
    plt.xlim(0, x_axis.max())
    plt.ylim(y_axis[1], 22050)
    plt.xlabel('Time (seconds)')
    plt.ylabel('Frequency (Hz)')
    plt.tick_params(axis='y', which='minor')
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    plt.colorbar(im, cax=cax, ticks = np.arange(0, -140, -20),
                 label = 'Power (dB)')
    plt.savefig('../Web_Interface/output/spectra/' + title + '.png')
    if not custom is None:
        if dry == True:
            plt.savefig('../Web_Interface/static/temp_dry.png')
        else:
            plt.savefig('../Web_Interface/static/temp_wet.png')
    else:
        plt.savefig(custom)
Example #20
0
 def plot_sleipner_thick_contact(self, years, gwc = False, sim_title = ''):
     if gwc == True:
         tc_str = 'contact'
     else:
         tc_str = 'thickness'
     yr_indices = self.get_plan_year_indices(years)
     size = 14
     font = {'size' : size}
     matplotlib.rc('font', **font)
     fig = plt.figure(figsize=(10.0, 2.5), dpi = 960)
     middle = len(years) * 10
     pos = 100 + middle
     for n in range(len(yr_indices)):
         pos +=1
         ax = fig.add_subplot(pos)
         xf = []
         yf = []
         kf = []
         for i in range(self.nx):
             tempx = []
             tempy = []
             tempk = []
             for j in range(self.ny):
                 x = self.x[(i, j, 0)]
                 y = self.y[(i, j, 0)]
                 tn = yr_indices[n]
                 thick, contact = self.get_thick_contact(i, j, tn)
                 tempx.append(x)
                 tempy.append(y)
                 if gwc == True:
                     tempk.append(contact)
                 else:
                     tempk.append(thick)
             xf.append(tempx)
             yf.append(tempy)
             kf.append(tempk)
         xp = np.asarray(xf)
         yp = np.asarray(yf)
         kp = np.asarray(kf)
         N = 10
         contour_label = False
         ax_label = False
         c = ax.contourf(xp, yp, kp, N)
         plt.tick_params(which='major', length=3, color = 'w')
         if n == len(years) - 1:
             fig.subplots_adjust(right=0.84)
             cb_axes = fig.add_axes([0.85, 0.15, 0.05, 0.7])
             plt.tick_params(which='major', length=3, color = 'k')
             cb = fig.colorbar(c, cax = cb_axes, format = '%.2f')
             cb.set_ticks(np.linspace(np.amin(kp), np.amax(kp), N))
             cb.set_label(tc_str + ': [m]')
         if n != 0:
             ax.set_yticklabels([])
         ax.set_xticklabels([])
         ax.set_title(str(years[n]))
         ax.axis([0, 3000, 0, 6000])
         ax.xaxis.set_ticks(np.arange(0,3500,1000))
     plt.savefig(sim_title + '_' +  tc_str + '.pdf', fmt = 'pdf')
     plt.clf()
     return 0
def plotFaultStatus(time, faultStatus, ax):
    """
    This function plots the estimated faults statuses and the actual
    faults. This plot is helpful to understand to place in a specific
    context the estimations of the algorithm.
    """
    ax.plot(time, faultStatus[:,0],'k--',label='$F_{Leak}$')
    ax.plot(time, faultStatus[:,1],'k',label='$F_{Stuck}$')
    
    t0 = pd.to_datetime(96.4, unit = "s", utc = True)
    t1 = pd.to_datetime(150.0, unit = "s", utc = True)
    t2 = pd.to_datetime(169, unit = "s", utc = True)
    t3 = pd.to_datetime(360.0, unit = "s", utc = True)
    ax.fill_between([t0, t1], [-10, -10], [0.5,0.5], facecolor='red', interpolate=True, alpha=0.2)
    ax.fill_between([t2, t3], [0.5, 0.5], [10,10], facecolor='red', interpolate=True, alpha=0.2)
    ax.set_xlim([time[0], time[-1]])
    ax.set_ylim([0.0, 1.0])
    ax.set_xlabel('Time')
    ax.set_ylabel('Faults')
    
    t4 = pd.to_datetime(200, unit = "s", utc = True)
    t5 = pd.to_datetime(110, unit = "s", utc = True)
    plt.text(t4, 0.75, "Stuck")
    plt.text(t5, 0.25, "Leak")
    plt.tick_params(\
        axis='y',          # changes apply to the y-axis
        which='both',      # both major and minor ticks are affected
        bottom='off',      # ticks along the bottom edge are off
        top='off',         # ticks along the top edge are off
        left='off',
        right='off',
        labelleft='off',
        labelbottom='off') # labels along the bottom edge are off
    return
Example #22
0
def ARMA(timeseries):
	# Input how many lags
	print ('\nHow many AR lags?')
	p = int(input())
	print ('\nHow many MA lags?')
	q = int(input())
	print ('\nDifferenced? Y/N')
	d = 1 if input() == 'Y' else 0
	arma_mod = sm.tsa.ARIMA(timeseries, order=(p, d, q))
	arma_res = arma_mod.fit(trend='nc', disp=-1)
	print (arma_res.summary())
	# Plot ARIMA w/ predictions
	fig, ax = plt.subplots()
	ax = timeseries.ix[1:].plot(ax=ax)
	plt.tick_params(axis="both", which="both", bottom="on", top="off",    
		                labelbottom="on", left="on", right="off", labelleft="on")
	print('When would you like to start forecast? DD-MM-YYY')
	pred_start = (input())
	print('When would you like to stop forecast? DD-MM-YYY (e.g. one year ahead)')
	pred_end = (input())
	arma_res.plot_predict(start=pred_start, end=pred_end, dynamic=False, ax=ax, plot_insample=False)	
	plt.xlabel("Year", fontsize=14) 
	plt.title('ARIMA', fontsize=15)
	plt.tight_layout()
	fig.savefig('arma.png', bbox_inches="tight")
Example #23
0
def graph(csv_file, filename, bytes2str):
    '''Create a line graph from a two column csv file.'''

    unit = configs['unit']
    date, value = np.loadtxt(csv_file, delimiter=',', unpack=True,
                             converters={0: bytes2str}
                             )
    fig = plt.figure(figsize=(10, 3.5))
    fig.add_subplot(111, axisbg='white', frameon=False)
    rcParams.update({'font.size': 9})
    plt.plot_date(x=date, y=value, ls='solid', linewidth=2, color='#FB921D',
                  fmt=':'
                  )
    title = "Sump Pit Water Level {}".format(time.strftime('%Y-%m-%d %H:%M'))
    title_set = plt.title(title)
    title_set.set_y(1.09)
    plt.subplots_adjust(top=0.86)

    if unit == 'imperial':
        plt.ylabel('inches')
    if unit == 'metric':
        plt.ylabel('centimeters')

    plt.xlabel('Time of Day')
    plt.xticks(rotation=30)
    plt.grid(True, color='#ECE5DE', linestyle='solid')
    plt.tick_params(axis='x', bottom='off', top='off')
    plt.tick_params(axis='y', left='off', right='off')
    plt.savefig(filename, dpi=72)
Example #24
0
def SetAxes(legend=False):
    f_b = 0.164
    f_star = 0.01
    err_b = 0.006
    err_star = 0.004
    f_gas = f_b - f_star
    err_gas = np.sqrt(err_b**2 + err_star**2)

    plt.axhline(y=f_gas, ls='--', c='k', label='', zorder=-1)
    x = np.linspace(.0,2.,1000)
    plt.fill_between(x, y1=f_gas - err_gas, y2=f_gas + err_gas, color='k', alpha=0.3, zorder=-1)
    plt.text(.6, f_gas+0.006, r'f$_{gas}$', verticalalignment='bottom', size='large')
    plt.xlabel(r'r/r$_{vir}$', size='x-large')
    plt.ylabel(r'f$_{gas}$ ($<$ r)', size='x-large')

    plt.xscale('log')
    plt.xticks([1./1.9, 1.33/1.9, 1, 1.5, 2.],[r'r$_{500}$', r'r$_{200}$', 1, 1.5, 2], size='large')
    #plt.yticks([.1, .2], ['0.10', '0.20'])
    plt.tick_params(length=10, which='major')
    plt.tick_params(length=5, which='minor')
    plt.xlim([0.4,1.5])
    plt.minorticks_on()

    if legend:
        plt.legend(loc=0, prop={'size':'small'}, markerscale=0.7, numpoints=1, ncol=2)
Example #25
0
def histogram(x, y, xlabel=None, ylabel=None, title=None, out=None, highlight=None):
    plt.bar(range(len(x)), y, color='b', alpha=0.6, linewidth=0, align='center')

    # if highlight is not None:
    #     barlist[highlight].set_color('r')
    #     rect = barlist[highlight]
    #     height = rect.get_height()
    #     width = rect.get_width()
    #     plt.text(rect.get_x() + width/2., height+1, "%.2f%%" % float(height), ha='center', va='center')

    plt.xticks(range(len(x)), x, ha='center', va='top', rotation='vertical')
    plt.tick_params(axis='y', labelsize='x-small')
    # plt.xlim([-1, len(x)])
    # plt.ylim([0, y[0]+((y[0]/100)*10)])
    # plt.axis('auto')
    # plt.title(title)
    plt.gca().yaxis.grid(True)


    if xlabel != None and ylabel != None:
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)

    if out == None:
        plt.show()
    else:
        plt.savefig("../PLOT/" + out + ".jpg")
        plt.show()
def histogram(X, z, colors=['#1F77B4', '#FF7F0E'], fname='plot.pdf',
              xlim=None, bins=500):
    """Plot histograms of 1-dimensional data.
    
    Input: X = data matrix
           z = class labels
           color = color for each class
           fname = output file

    Output: None

    """
    z_unique = np.unique(z)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    colors = iter(colors)
    for k in z_unique:
        idx = np.where(z==k)[0]
        x = X[idx]
        ax.hist(x, bins=bins, facecolor=next(colors), 
                histtype='stepfilled',
                alpha=.8, normed=1, linewidth=0.5)
    ax.set_xlabel(r'$x$')
    if xlim:
        ax.set_xlim(xlim)
    plt.tick_params(top='off', bottom='on', left='off', right='off',
            labelleft='off', labelbottom='on')
    for i, spine in enumerate(plt.gca().spines.values()):
        if i !=2:
            spine.set_visible(False)
    frame = plt.gca()
    frame.axes.get_yaxis().set_visible(False)
    fig.tight_layout()
    fig.savefig(fname)
Example #27
0
def drawMean(ctype, filename, titulo, yaxis, comp, *args):
    plt.switch_backend('Qt4Agg')
    fig = plt.figure(figsize=(28, 5))
    ax = fig.add_subplot(1,2,1)
    means = []
    for v in comp:
        means.append(np.mean(v))
    col = ['r', 'b', 'g', 'm', 'c', 'y', 'r', 'b', 'g', 'm', 'c', 'y']
    if len(comp) == 16:
        col = ['r', 'r', 'g', 'g', 'g', 'b', 'b', 'b', 'c', 'c', 'c', 'm', 'm', 'm', 'y', 'y', 'y' ]
    if len(comp) == 12:
        col = ['r', 'r' ,'b','b','g', 'g','m', 'm', 'c', 'c', 'y' ,'y']
    if len(comp) == 13:
        col = ['r', 'r', 'r','b','b','g', 'g','m', 'm', 'c', 'c', 'y' ,'y']
    if len(comp) == 11:
        col = ['r' ,'b','b','g', 'g','m', 'm', 'c', 'c', 'y' ,'y']
    ax.grid( b=True, linestyle='-',  axis = 'y', linewidth=1, zorder=1) 
    if len(comp) < 7:
        ax.bar( range(1, int(ctype) + 1),  means, align='center', color=col[0: int(ctype) + 1], zorder = 10, width = 0.6)
    else:
        ax.bar( range(1, int(ctype) + 1),  means, align='center', color=col[0: int(ctype) + 1], zorder = 10)
    plt.title(titulo)
    labels = [i for i in args]
    plt.ylabel(yaxis+' (promedio)')
    plt.tick_params(labelsize = 7)
    plt.xticks(range(1, (int(ctype)) + 1), labels)
    plt.savefig(filename+' (promedio).png', bbox_inches = 'tight')
    plt.xticks()
    val_strings = ["%10.10f" % x for x in means ]
    with open(filename + '_promedio.txt', 'w') as file_:
        for k in range(0, len(comp)):
            file_.write(labels[k] + " " + val_strings[k] + "\n")
Example #28
0
def stationarity(timeseries):
	#Determing rolling statistics
	rol_mean = timeseries.rolling(window=12).mean()
	rol_std = timeseries.rolling(window=12).std()
	#Plot rolling statistics:
	fig, ax = plt.subplots()
	plt.grid(color='grey', which='major', axis='y', linestyle='--')
	plt.plot(timeseries, color='blue', label='Original', linewidth=1.25)
	plt.plot(rol_mean, color='red', label='Rolling Mean', linewidth=1.25)
	plt.plot(rol_std, color='black', label = 'Rolling Std', linewidth=1.25)
	plt.legend(loc='best')
	title = headers[1], data[index].iloc[0], '-' ,data[index].iloc[-1]
	plt.title(title)
	plt.tick_params(axis="both", which="both", bottom="on", top="off",    
		            labelbottom="on", left="off", right="off", labelleft="on")
	ax.spines['right'].set_visible(False)
	ax.spines['top'].set_visible(False)
	ax.xaxis.set_ticks_position('bottom') 
	fig.title = ('stationarity.png')
	fig.savefig(fig.title, bbox_inches="tight")
	#Perform Dickey-Fuller test:
	print ('Results of Dickey-Fuller Test:\n')
	df_test = adfuller(timeseries, autolag='AIC')
	df_output = pd.Series(df_test[0:4], index=['Test Statistic','p-value','#Lags Used','No. of Observations Used'])
	for key,value in df_test[4].items():
	    df_output['Critical Value (%s)'%key] = value
	print (df_output.round(3))
def draw_filters(W, cols=20, fig_size=(10, 10), filter_shape=(28, 28),
                 filter_standardization=False):
    border = 2
    num_filters = len(W)
    rows = int(np.ceil(float(num_filters) / cols))
    filter_height, filter_width = filter_shape

    if filter_standardization:
        W = preprocessing.scale(W, axis=1)
    image_shape = (rows * filter_height + (border * rows),
                   cols * filter_width + (border * cols))
    low, high = W.min(), W.max()
    low = (3 * low + high) / 4
    high = (low + 3 * high) / 4
    all_filter_image = np.random.uniform(low=low, high=high,
                                         size=image_shape)
    all_filter_image = np.full(image_shape, W.min(), dtype=np.float32)

    for i, w in enumerate(W):
        start_row = (filter_height * (i / cols) +
                     (i / cols + 1) * border)
        end_row = start_row + filter_height
        start_col = (filter_width * (i % cols) +
                     (i % cols + 1) * border)
        end_col = start_col + filter_width
        all_filter_image[start_row:end_row, start_col:end_col] = \
            w.reshape(filter_shape)

    plt.figure(figsize=fig_size)
    plt.imshow(all_filter_image, cmap=plt.cm.gray,
               interpolation='none')
    plt.tick_params(axis='both',  labelbottom='off',  labelleft='off')
    plt.show()
def plot_date_bars(bin_data, bin_edges, title, ylabel, fname):
    """
    Semi-generic function to plot a bar graph, x-label is fixed to "date" and the
    x-ticks are formatted accordingly.

    To plot a histogram, the histogram data must be calculated manually outside
    this function, either manually or using :py:func`numpy.histogram`.

    :param bin_data: list of data for each bin
    :param bin_edges: list of bin edges (:py:class:`datetime.date` objects), its
                      length must be ``len(data)+1``
    :param title: title of the plot
    :param ylabel: label of y-axis
    :param fname: output file name
    """
    import matplotlib.pyplot as plt
    from matplotlib.dates import date2num, num2date
    from matplotlib import ticker

    plt.figure()  # clear previous figure
    plt.title(title)
    plt.xlabel("date")
    plt.ylabel(ylabel)

    # plot the bars, width of the bins is assumed to be fixed
    plt.bar(date2num(bin_edges[:-1]), bin_data, width=date2num(bin_edges[1]) - date2num(bin_edges[0]))

    # x-ticks formatting
    plt.gca().xaxis.set_major_formatter(ticker.FuncFormatter(lambda numdate, _: num2date(numdate).strftime('%Y-%m-%d')))
    plt.gcf().autofmt_xdate()
    plt.tick_params(axis="x", which="both", direction="out")
    plt.xticks([date2num(ts) for ts in bin_edges if ts.month % 12 == 1])

    plt.savefig(fname, papertype="a4")
Example #31
0
    def plotTri(self,section,paramList,setNames,cols=itertools.repeat(None),lss=itertools.repeat(None),labels=itertools.repeat(None),saveFile="default.png",levels=[2.],xlims=None,ylims=None,loc='upper right',centerMarker=True,TwoSig=False,**kwargs):

        circl = self.circl
        numpars = len(paramList)
        thk = 3

        matplotlib.rc('axes', linewidth=thk)
        fig=plt.figure(figsize=(4*numpars,4*numpars),**kwargs)
        
        if cols is None: cols = itertools.repeat(None)

        for setName,col,ls,lab in zip(setNames,cols,lss,labels):
            gaussOnly, fisher = self.fishers[section][setName]
            Finv = np.linalg.inv(fisher)
            for i in range(0,numpars):
                for j in range(i+1,numpars):
                    count = 1+(j-1)*(numpars-1) + i

                    paramX = paramList[i]
                    paramY = paramList[j]

                    p = self.paramLists[section].index(paramX)
                    q = self.paramLists[section].index(paramY)

                    chi211 = Finv[p,p]
                    chi222 = Finv[q,q]
                    chi212 = Finv[p,q]

                    # a sigma8 hack
                    if "S8" in paramX:
                        xval = 0.8
                        paramlabelx = '$\sigma_8(z_{'+paramX[3:]+'})$'
                    else:
                        xval = self.fidDicts[section][paramX]
                        paramlabelx = '$'+self.paramLatexLists[section][p]+'$'
                    if "S8" in paramY:
                        yval = 0.8
                        paramlabely = '$\sigma_8(z_{'+paramY[3:]+'})$'
                    else:
                        yval = self.fidDicts[section][paramY]
                        paramlabely = '$'+self.paramLatexLists[section][q]+'$' 

                    if paramX=="S8All": paramlabelx = '$\sigma_8$'
                    if paramY=="S8All": paramlabely = '$\sigma_8$'
                        
                    chisq = np.array([[chi211,chi212],[chi212,chi222]])
                    Lmat = np.linalg.cholesky(chisq)
                    ansout = np.dot(1.52*Lmat,circl)
                    ansout2 = np.dot(2.0*1.52*Lmat,circl)
                    
                    
                    ax = fig.add_subplot(numpars-1,numpars-1,count)
                    plt.tick_params(size=14,width=thk,labelsize = 11)
                    if centerMarker: ax.plot(xval,yval,'xk',mew=thk)
                    ax.plot(ansout[0,:]+xval,ansout[1,:]+yval,linewidth=thk,color=col,ls=ls,label=lab)
                    if TwoSig:
                        ax.plot(ansout2[0,:]+xval,ansout2[1,:]+yval,linewidth=thk,color=col,ls=ls)
                    if (i==0):#(count ==1):
                        ax.set_ylabel(paramlabely, fontsize=32,weight='bold')
                    if (j == (numpars-1)):
                        ax.set_xlabel(paramlabelx, fontsize=32,weight='bold')
                    
        
        labsize = 48
        handles, labels = ax.get_legend_handles_labels()
        legend = fig.legend(handles, labels,prop={'size':labsize},numpoints=1,frameon = 0,loc=loc, bbox_to_anchor = (-0.1,-0.1,1,1),bbox_transform = plt.gcf().transFigure,**kwargs) #

        plt.savefig(saveFile, bbox_inches='tight',format='png')
        print(bcolors.OKGREEN+"Saved plot to", saveFile+bcolors.ENDC)
import matplotlib.pyplot as plt


x_values = list(range(5001))
y_values = [x**3 for x in x_values]

plt.figure(figsize=(9, 6))
plt.scatter(x_values, y_values, edgecolors=None,
            c=y_values, cmap=plt.cm.YlOrRd, s=3)

# Labels and axis
plt.title('Cubes of Numbers', fontsize=22)
plt.xlabel('Number', fontsize=14)
plt.ylabel('Value of Cube', fontsize=14)

# Tick label size
plt.tick_params(axis='both', which='major', labelsize=14)

# x, y axis range
plt.axis([0, 5500, 0, 5100**3])

plt.savefig('./generating_data/images/cubes_plot_5000.png')
plt.show()
Example #33
0
        data = [float(substr) for substr in line.split(',')]
        train_x.append(data[:-1])
        train_y.append(data[-1])
# 二维数组形式的输入矩阵,一行一样本,一列一特征
train_x = np.array(train_x)
# 一维数组形式的输出序列,每个元素对应一个输入样本
train_y = np.array(train_y)
# 将一个多项式特征扩展预处理器和
# 一个线性回归器串联为一个管线
model = pl.make_pipeline(sp.PolynomialFeatures(10), lm.LinearRegression())
# 用已知的输入和输出训练线性回归器
model.fit(train_x, train_y)
# 根据给定的输入预测对应的输出
pred_train_y = model.predict(train_x)
# R2得分[0,1]
print(sm.r2_score(train_y, pred_train_y))
# 在训练集之外构造测试集
test_x = np.linspace(train_x.min(), train_x.max(), 1000)[:, np.newaxis]
pred_test_y = model.predict(test_x)
# 可视化回归曲线
mp.figure('Polynomial Regression', facecolor='lightgray')
mp.title('Polynomial Regression', fontsize=20)
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
mp.scatter(train_x, train_y, c='dodgerblue', alpha=0.75, s=60, label='Sample')
mp.plot(test_x, pred_test_y, c='orangered', label='Regression')
mp.legend()
mp.show()
import matplotlib

x = np.arange(0.01, 10, 0.05)
y = np.arange(0.01, 10, 0.05)
X, Y = np.meshgrid(x, y)
m = np.array([1.0, 2.0])

Z = X + Y - m[0] - m[1] - X * np.log(X/m[0]) - Y * np.log(Y/m[1])

fig = plt.figure()
ax = plt.axes()
plt.pcolormesh(X, Y, Z, cmap='magma')
pp=plt.colorbar (orientation="vertical")
plt.rcParams['font.size'] = 16
plt.rcParams['xtick.labelsize'] = 16
plt.rcParams['ytick.labelsize'] = 16
matplotlib.rcParams['ps.useafm'] = True
matplotlib.rcParams['pdf.use14corefonts'] = True

cont=plt.contour(X,Y,Z,8,vmin=-1,vmax=1, colors=['black'])
cont.clabel(fmt='%1.1f', fontsize=16)
plt.plot(1.0,2.0,marker='.',markersize=16)
plt.xlabel(r'$x_1$', fontsize=16)
plt.ylabel(r'$x_2$', fontsize=16)
plt.tick_params(which='major', labelsize=16)
plt.gca().set_aspect('equal')

ppdf = PdfPages('information_entropy.pdf')
ppdf.savefig(fig,bbox_inches="tight", pad_inches=0.0)
ppdf.close()
Example #35
0
    def make(self, regions=[], title='',
        y_title=1.1, fs_title=20,
        fs_subtitle=10, fs_xlabel=16, fs_ylabel=16,
        fs_clabel=10, fs_legend=12, pad_clabel=10,
        xy_legend=(0, 0), xy_cbar=(0, 0),
        width=14, height=26,
        save_file=False, filename='', dpi=1200,
    ):
        self.subcats_keys = np.arange(1, len(self._casestudy.STRINDEX_SUBCATS) + 1)
        self.subcats_key = {tup[0]: tup[1] for tup in zip(self.subcats_keys, reversed(self._casestudy.STRINDEX_SUBCATS))}

        if regions:
            regions = accept_string_or_list(regions)
        else:        
            regions = self.regions
        regions = copy.deepcopy(regions)

        input_key = {reg: self._inputs_for_scatter(reg) for reg in regions}
        
        # Shape grid into appropriate size for number of regions
        # Create empty plot for first box and last box
        if len(regions) > 1 and len(regions) <= 3:
            regions.insert(0, '')
            if len(regions) % 2 != 0:
                regions += ['']
            regions = np.array(regions).reshape(-1, 2)
        elif len(regions) > 3 and len(regions) <= 8: 
            regions.insert(0, '')
            while True:
                if len(regions) % 3 != 0:
                    regions += ['']
                else:
                    break
            regions = np.array(regions).reshape(-1, 3)
        elif len(regions) > 8: 
            regions.insert(0, '')
            while True:
                if len(regions) % 4 != 0:
                    regions += ['']
                else:
                    break
            regions = np.array(regions).reshape(-1, 4)
        else:
            regions = np.array(regions)
        
        fig, axs = plt.subplots(*regions.shape, figsize=(width, height))
        cmap = plt.cm.get_cmap('RdPu', 4)

        strindex_labels = [self.labels[val] for val in self.subcats_key.values()]
        if not isinstance(axs, np.ndarray):
            axs = np.array([axs])
        for i, region in np.ndenumerate(regions):    
            if region:
                i = i[1] if axs.shape == (2,) else i
                xs, ys, zs = input_key[region]
                sc = axs[i].scatter(xs, ys, c=zs, vmin=zs.min(), vmax=zs.max(), cmap=cmap)
                axs[i].set_yticks(self.subcats_keys)
                axs[i].set_yticklabels(self.subcats_key.values() if regions.size > 1 else strindex_labels, fontsize=fs_ylabel)
                axs[i].set_title(region, fontsize=fs_subtitle,  fontweight='demibold')
            else:
                # Add legend in the first box
                if i == (0,0):
                    axs[i].set_title('LEGEND', 
                        {
                            'alpha': 1, 'color': 'black', 'va': 'center', 
                            'fontweight': 'demibold', 'fontsize': fs_subtitle
                        }
                    ) 
                    legend_text = ''
                    for val in reversed(list(self.subcats_key.values())):
                        legend_text += '\n{}: {}'.format(val, self.labels[val])

                    axs[i].text(*xy_legend, legend_text, 
                        {
                            'alpha': 1, 'color': 'black', 'fontsize': fs_legend, 'ha': 'left', 'va': 'center', 
                            'bbox':dict(facecolor='white', alpha=1, edgecolor='white')
                        }
                    )
                # Remove spines and other features for first and last box
                axs[i].tick_params(axis='both', which='both', length=0)
                axs[i].spines['right'].set_visible(False)
                axs[i].spines['top'].set_visible(False)
                axs[i].spines['left'].set_visible(False)
                axs[i].spines['bottom'].set_visible(False)

                plt.setp(axs[i].get_xticklabels(), visible=False)
                plt.setp(axs[i].get_yticklabels(), visible=False)

        # COLOR BAR SETUP
        if regions.size == 1:
            axis_for_color_bar = axs[0] 
            cb_ticks_pos = 'right'
            cb_label_pos = 'right'
        else:
            axis_for_color_bar = axs[0, 0]
            cb_ticks_pos = 'left'
            cb_label_pos = 'left'
        
        cax = inset_axes(axis_for_color_bar,
            width='6%',
            height='70%',
            loc='lower left',
            bbox_to_anchor=(*xy_cbar, .3, 1),
            bbox_transform=axis_for_color_bar.transAxes,
            borderpad=0,
        )
        cb = fig.colorbar(
            sc, extend='both', 
            cax=cax, orientation='vertical',
        )
        cb.set_label('Score', labelpad=pad_clabel, fontsize=fs_clabel)
        cax.yaxis.set_ticks_position(cb_ticks_pos)
        cax.yaxis.set_label_position(cb_label_pos)
        
        ax = fig.add_subplot(111, frameon=False)
        plt.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off', length=0)
        ax.set_title(title, fontsize=fs_title, y=y_title)
        ax.set_xlabel(self.labels['days_' + self.start_factor], labelpad=20, fontsize=fs_xlabel)
        plt.subplots_adjust(left=.1, bottom=.1, right=1, top=1, wspace=0.2, hspace=0.22)
        
        if save_file:
            plt.savefig(filename, bbox_inches='tight', dpi=dpi)

        return plt
Example #36
0
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt


df = pd.read_csv('startbucks.csv')
print(df)
# grouped=df.groupby('city').apply(lambda x:x.count())#各城市星巴克数量
grouped=df.groupby('city').size()#各城市星巴克数量
print(grouped.index)
print(type(grouped))
squares=[]
for x in grouped.index:
    squares.append(grouped[x])
print(squares)

plt.plot(squares, linewidth=5)  # 这里只指定了一个列表,那么就当作是输出参数,输入参数从0开始,就会发现没有正确绘制数据
plt.title("Square Numbers", fontsize=24)  # 指定标题,并设置标题字体大小
plt.xlabel("Value", fontsize=14)  # 指定X坐标轴的标签,并设置标签字体大小
plt.ylabel("Square of Value", fontsize=14)  # 指定Y坐标轴的标签,并设置标签字体大小
plt.tick_params(axis='both', labelsize=14)  # 参数axis值为both,代表要设置横纵的刻度标记,标记大小为14
plt.show()  # 打开matplotlib查看器,并显示绘制的图形
Example #37
0
def coefvis(predictor, model, fontsize=4):
    """predictor = parameter whose estimate you want to understand
    model = linear model object from statsmodels.formula.api.ols
    saves csvs and heatmap pngs in a folder
    returns figure, axes"""
    results = model.fit()
    print(results.params)
    coeffs = results.params
    predictors = model.exog_names
    endog = model.endog.reshape((-1, 1))
    exog = model.exog
    data = pd.DataFrame(data=np.hstack((exog, endog)),
                        columns=np.append(model.exog_names, model.endog_names))
    if "Intercept" in predictors:
        predictors.remove("Intercept")
        data = data.drop("Intercept", axis=1)
    if not os.path.exists(predictor):
        os.makedirs(predictor)
    if not os.path.isfile(predictor + "/" + predictor + ".csv"):
        table = pd.DataFrame()
        for i in range(len(data.index)):
            if data[predictor][i] != 0:
                table = table.append(data.iloc[i, :])
        for j in table:
            if all([x == 0 for x in table[j]]):
                del table[j]
        del table[predictor]
        table.to_csv(predictor + "/" + predictor + ".csv", index=False)
    table = pd.read_csv(predictor + "/" + predictor + ".csv")
    array = table.drop([col for col in data.columns if col not in predictors],
                       axis=1)
    array.index = [round(x, ndigits=2) for x in table[model.endog_names]]
    for a in array.columns:
        array[a] = array[a] * coeffs[a]
    array = array[array.columns].astype(float)
    np_array = np.array(array)
    fig, ax = plt.subplots()
    heatmap = plt.pcolor(np_array)
    plt.colorbar(heatmap)
    length = len(array.columns)
    for y in range(np_array.shape[0]):
        for x in range(np_array.shape[1]):
            plt.text(x + 0.5,
                     y + 0.5,
                     '%.1f' % np_array[y, x],
                     horizontalalignment='center',
                     verticalalignment='center',
                     fontsize=fontsize)
    for y in range(np_array.shape[0]):
        plt.text(-0.5,
                 y + 0.5,
                 '%.1f' % array.index[y],
                 horizontalalignment='center',
                 verticalalignment='center',
                 fontsize=fontsize)
    for x in range(np_array.shape[1]):
        plt.text(x + 0.5,
                 -1,
                 '%s' % array.columns[x],
                 horizontalalignment='center',
                 verticalalignment='center',
                 fontsize=fontsize)
    plt.tick_params(axis='x', which='both', bottom='on', top='off')
    plt.tick_params(axis='y', which='both', left='on', right='off')
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    ax.spines['left'].set_position('zero')
    ax.spines['bottom'].set_position('zero')
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    plt.title("%s=%.1f" % (predictor, coeffs[predictor]))
    fig.subplots_adjust(bottom=0.2)
    fig.savefig(predictor + "/" + predictor + ".png", dpi=500)
    return fig, ax
Example #38
0
# 给你前面绘制的立方图指定颜色映射。

# 绘制5000个
import matplotlib.pyplot as plt

# 绘制5000个
x_values = list(range(1,5001))
values2 = [ x**3 for x in x_values]
plt.scatter(x_values, values2, c = values2, cmap=plt.cm.BuGn, edgecolors='none', s=40)

plt.title("Cubes", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Cube of Value', fontsize=14)
plt.tick_params(axis='both', labelsize=14)

plt.show()
Example #39
0
                        limit=args.tolerance,
                        K=2)

                    plot_greens(greens,
                                alphas=alphas,
                                mus=mus,
                                sigmas=sigmas,
                                ax=axes[1][3])
                except ZeroDivisionError:
                    logger.log('Error plotting green levels')
                    axes[1][3].scatter(0, 0, c='r', s=300, marker='x')
                    axes[1][3].set_title('Error plotting green levels')
                    plt.tick_params(axis='both',
                                    which='both',
                                    bottom='off',
                                    top='off',
                                    labelbottom='off',
                                    right='off',
                                    left='off',
                                    labelleft='off')
            plt.savefig(
                fcs.get_image_name(
                    script=os.path.basename(__file__).split('.')[0],
                    plate=plate,
                    well=well))
            if not args.show:
                plt.close()

        mappingBuilder.save()
        regressionTracker.save()

        end = time()
Example #40
0
    def __init__(self,scheme=None,xlabel=None,ylabel=None,xyscale=None,xscale="linear",yscale="linear",ftsize=14,thk=1,labsize=None,major_tick_size=5,minor_tick_size=3,scalefn = None,**kwargs):
        self.scalefn = None
        if scheme is not None:
            if scheme=='Dell' or scheme=='Dl':
                xlabel = '$\\ell$' if xlabel is None else xlabel
                ylabel = '$D_{\\ell}$' if ylabel is None else ylabel
                xyscale = 'linlog' if xyscale is None else xyscale
                self.scalefn = (lambda x: x**2./2./np.pi) if scalefn is None else scalefn
            elif scheme=='Cell' or scheme=='Cl':
                xlabel = '$\\ell$' if xlabel is None else xlabel
                ylabel = '$C_{\\ell}$' if ylabel is None else ylabel
                xyscale = 'linlog' if xyscale is None else xyscale
                self.scalefn = (lambda x: 1)  if scalefn is None else scalefn
            elif scheme=='CL':
                xlabel = '$L$' if xlabel is None else xlabel
                ylabel = '$C_{L}$' if ylabel is None else ylabel
                xyscale = 'linlog' if xyscale is None else xyscale
                self.scalefn = (lambda x: 1)  if scalefn is None else scalefn
            elif scheme=='LCL':
                xlabel = '$L$' if xlabel is None else xlabel
                ylabel = '$LC_{L}$' if ylabel is None else ylabel
                xyscale = 'linlin' if xyscale is None else xyscale
                self.scalefn = (lambda x: x)  if scalefn is None else scalefn
            elif scheme=='rCell' or scheme=='rCl':
                xlabel = '$\\ell$' if xlabel is None else xlabel
                ylabel = '$\\Delta C_{\\ell} / C_{\\ell}$' if ylabel is None else ylabel
                xyscale = 'linlin' if xyscale is None else xyscale
                self.scalefn = (lambda x: 1)  if scalefn is None else scalefn
            elif scheme=='dCell' or scheme=='dCl':
                xlabel = '$\\ell$' if xlabel is None else xlabel
                ylabel = '$\\Delta C_{\\ell}$' if ylabel is None else ylabel
                xyscale = 'linlin' if xyscale is None else xyscale
                self.scalefn = (lambda x: 1)  if scalefn is None else scalefn
            elif scheme=='rCL':
                xlabel = '$L$' if xlabel is None else xlabel
                ylabel = '$\\Delta C_{L} / C_{L}$' if ylabel is None else ylabel
                xyscale = 'linlin' if xyscale is None else xyscale
                self.scalefn = (lambda x: 1)  if scalefn is None else scalefn
            else:
                raise ValueError
        if self.scalefn is None: 
            self.scalefn = (lambda x: 1) if scalefn is None else scalefn
        if xyscale is not None:
            scalemap = {'log':'log','lin':'linear'}
            xscale = scalemap[xyscale[:3]]
            yscale = scalemap[xyscale[3:]]
        matplotlib.rc('axes', linewidth=thk)
        matplotlib.rc('axes', labelcolor='k')
        self.thk = thk
        
        self._fig=plt.figure(**kwargs)
        self._ax=self._fig.add_subplot(1,1,1)


        # Some self-disciplining :)
        try:
            force_label = os.environ['FORCE_ORPHICS_LABEL']
            force_label = True if force_label.lower().strip() == "true" else False
        except:
            force_label = False

        if force_label:
            assert xlabel is not None, "Please provide an xlabel for your plot"
            assert ylabel is not None, "Please provide a ylabel for your plot"



        if xlabel!=None: self._ax.set_xlabel(xlabel,fontsize=ftsize)
        if ylabel!=None: self._ax.set_ylabel(ylabel,fontsize=ftsize)

        self._ax.set_xscale(xscale) 
        self._ax.set_yscale(yscale)


        if labsize is None: labsize=ftsize-2
        plt.tick_params(axis='both', which='major', labelsize=labsize,width=self.thk,size=major_tick_size)#,size=labsize)
        plt.tick_params(axis='both', which='minor', labelsize=labsize,size=minor_tick_size)#,size=labsize)
        self.do_legend = False
Example #41
0
            ff = False
            continue
        else:
            x = np.append(x, float(line[ep]))
    print(x)
    """
    mu, sigma = 100, 15

    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)

    ax.hist(x, bins=50)
    ax.set_title('first histogram $\mu=100,\ \sigma=15$')
    ax.set_xlabel('x')
    ax.set_ylabel(label_y)
    fig.save(path+"\\sample"+str(ep)+".jpg")
    """
    vari = np.var(x)
    avr = np.average(x)
    y = 1 / np.sqrt(2 * np.pi * vari) * np.exp(-(x - avr)**2 / (2 * vari))
    plt.subplot(3, 3, ep + 1)
    plt.hist(x)
    # plt.plot(x,y)
    plt.title(label_y, fontsize=7)
    plt.xlabel("fluc", fontsize=7)
    plt.ylabel("num_seq", fontsize=7)
    plt.tick_params(labelsize=7)
    ff = True
    print(str(ep) + "th ending")
    ep += 1
plt.savefig(path + "\\sample" + str(ep) + ".png")
#author='zhy'
import matplotlib.pyplot as plt

input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]
plt.plot(input_values, squares, linewidth=5)

#设置图标标题,并给坐标轴加上标签
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)

#设置刻度标记的大小
plt.tick_params(axis="both", labelsize=14)

plt.show()
Example #43
0
def prettyCompare(xdata,ydata,yrange=[0.,1.],ylabel="No Label",datalabels=False,
                  title="No Title",caption=False,floatCaption=None,
                  logSpace=False,corePlot=False,plotType="line",
                  adjust=None,textSpace=0.,size=(12,9),xTickremove=None,
                  yTickremove=None, marginLeft=None,marginRight=None,
                  marginBottom=None,marginTop=None,
                  xLabelAdj=0.,yLabelAdj=0., xlabel=r"$\rho$",
                  toSN=False):
        
    prettyData=[xdata]
    for a in ydata:
        prettyData.append(a)
    pandasFrame=pd.DataFrame.from_items(prettyData)

#    These are the "Tableau 20" colors as RGB.    

#    tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),    
#                 (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),    
#                 (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),    
#                 (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),    
#                 (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]  

    tableau20 = [(255,0,0), (0,0,255), (0,255,0), (255,0,255),    
                 (128,0,0), (128,0,128), (0,0,128), (0,128,128)]              
#    
    for i in range(len(tableau20)):    
        r, g, b = tableau20[i]    
        tableau20[i] = (r / 255., g / 255., b / 255.)      

    fig=plt.figure(figsize=size)
    
#   Remove the plot frame lines. They are unnecessary chartjunk.    
    ax = plt.subplot(111)    
    ax.spines["top"].set_visible(False)    
    ax.spines["bottom"].set_visible(False)    
    ax.spines["right"].set_visible(False)    
    ax.spines["left"].set_visible(False)    

    plt.subplots_adjust(bottom=marginBottom,left=marginLeft,top=marginTop,right=marginRight)
#   Ensure that the axis ticks only show up on the bottom and left of the plot.    
#   Ticks on the right and top of the plot are generally unnecessary chartjunk.    
    ax.get_xaxis().tick_bottom()    
    ax.get_yaxis().tick_left()   
      
#   Limit the range of the plot to only where the data is.    
#   Avoid unnecessary whitespace.    
    plt.ylim(yrange[0],yrange[1])    
    if corePlot==True:
        plt.xlim(0,0.85+textSpace)     # core
        xrange=[0,.85]
    else:
        plt.xlim(.85,1+textSpace)    # edge
        xrange=[.85,1.]

#   Make sure your axis ticks are large enough to be easily read.    
#   You don't want your viewers squinting to read your plot. 
    if logSpace==False:
        if toSN!=False:
            if yTickremove!=None:
                plt.yticks(np.linspace(yrange[0],yrange[1],num=6)[:(-1*yTickremove)], [str(round(x,2)) for x in np.linspace(yrange[0]/(1.*10**toSN),yrange[1]/(1.*10**toSN),num=6)], fontsize=30)    
            else:
#                print np.linspace(yrange[0]/(10**toSN),yrange[1]/(1.*10**toSN),num=6)
                plt.yticks(np.linspace(yrange[0],yrange[1],num=6), [str(round(x,2)) for x in np.linspace(yrange[0]/(1.*10**toSN),yrange[1]/(1.*10**toSN),num=6)], fontsize=26)    
        elif yTickremove!=None:
            plt.yticks(np.linspace(yrange[0],yrange[1],num=6)[:(-1*yTickremove)], [str(round(x,2)) for x in np.linspace(yrange[0],yrange[1],num=6)], fontsize=30)    
        else:
            plt.yticks(np.linspace(yrange[0],yrange[1],num=6), [str(round(x,2)) for x in np.linspace(yrange[0],yrange[1],num=6)], fontsize=26)    
            
    else:
        if yTickremove!=None:
            plt.yticks([log(a) for a in np.logspace(yrange[0],yrange[1],num=6)][:(-1*yTickremove)],[str(round(x,2)) for x in [log(a) for a in np.logspace(yrange[0],yrange[1],num=6)]], fontsize=26)
        else:
            plt.yticks([log(a) for a in np.logspace(yrange[0],yrange[1],num=6)],[str(round(x,2)) for x in [log(a) for a in np.logspace(yrange[0],yrange[1],num=6)]], fontsize=26)
    
    plt.tick_params(axis='x',pad=18)



    if xTickremove!=None:
        plt.xticks(np.linspace(xrange[0],xrange[1],num=6)[:(-1*xTickremove)], [str(round(x,2)) for x in np.linspace(xrange[0],xrange[1],num=6)], fontsize=26)    
    else:
        plt.xticks(np.linspace(xrange[0],xrange[1],num=6), [str(round(x,2)) for x in np.linspace(xrange[0],xrange[1],num=6)], fontsize=26)    

        
#   Provide tick lines across the plot to help your viewers trace along    
#   the axis ticks. Make sure that the lines are light and small so they    
#   don't obscure the primary data lines. 
    if logSpace==False:        
        for y in np.linspace(yrange[0],yrange[1],num=6):    
            plt.plot(np.linspace(xrange[0],xrange[1],num=6), [y] * len(np.linspace(xrange[0],xrange[1],num=6)), "--", lw=0.5, color="black", alpha=0.3)     
    else:
        for y in [log(a) for a in np.logspace(yrange[0],yrange[1],num=6)]:    
            plt.plot([log(a) for a in np.logspace(yrange[0],yrange[1],num=6)], [y] * len([log(a) for a in np.logspace(yrange[0],yrange[1],num=6)]), "--", lw=0.5, color="black", alpha=0.3)     
        
#   Remove the tick marks; they are unnecessary with the tick lines we just plotted.    
    plt.tick_params(axis="both", which="both", bottom="off", top="off",    
                    labelbottom="on", left="off", right="off", labelleft="on")  
    ystep=(yrange[1]-yrange[0])/25.
    for rank, column in enumerate(datalabels):    
#       Plot each line separately with its own color, using the Tableau 20    
#       color set in order.    
        if plotType=="line":
            plt.plot(pandasFrame.rhor.values,
                     pandasFrame[column.replace("\n", " ")].values,    
                    lw=2.5, color=tableau20[rank])  
            y_pos=pandasFrame[column.replace("\n", " ")].values[-1]
        elif plotType=="scat":        
            plt.scatter(pandasFrame.rhor.values,
                    pandasFrame[column.replace("\n", " ")].values,    
                    color=tableau20[rank])                   
            y_pos=pandasFrame[column.replace("\n", " ")].values[-1]
        else:
            raise ("No line type requested")
        try:
            if rank in adjust.keys():
                y_pos += adjust[rank]*ystep

        except:
            pass
        
    # Again, make sure that all labels are large enough to be easily read    
    # by the viewer.    
        plt.text(xrange[1]+0.0025, y_pos, column, fontsize=20, color=tableau20[rank])  
    # matplotlib's title() call centers the title on the plot, but not the graph,    
    # so I used the text() call to customize where the title goes.    
      
    # Make the title big enough so it spans the entire plot, but don't make it    
    # so big that it requires two lines to show.    
      
    # Note that if the title is descriptive enough, it is unnecessary to include    
    # axis labels; they are self-evident, in this plot's case.    
#    plt.text((xrange[1]-xrange[0])/2.+xrange[0]+0.015, (yrange[1]-yrange[0])/20.+yrange[1], title, fontsize=26, ha="center")      
    plt.text((xrange[1]-xrange[0])/2.+xrange[0]+.5*textSpace, (yrange[1]-yrange[0])/20.+yrange[1], title, fontsize=26, ha="center")      

    if caption!=False:
        for num,cap in enumerate(caption):
            plt.text(xrange[0],yrange[0]-(yrange[1]-yrange[0])/7.5-(num)*(yrange[1]-yrange[0])/22.5,cap,fontsize=16,ha="left")
    if floatCaption!=None:
        plt.text(floatCaption[1][0],floatCaption[1][1],floatCaption[0],fontsize=22,ha="left",va="top")
        
    for num,label in enumerate(ylabel):
        plt.text(xrange[0]-(xrange[1]-xrange[0])/10.+yLabelAdj*(xrange[1]-xrange[0])/10.,(yrange[1]-yrange[0])/2.+yrange[0]-num*(yrange[1]-yrange[0])/10.,label,fontsize=38,ha="center")
            
    plt.text((xrange[1]-xrange[0])/2.+xrange[0],yrange[0]-(yrange[1]-yrange[0])/12.5+xLabelAdj*(yrange[1]-yrange[0]/10.),xlabel,fontsize=38,ha="center")
    
Example #44
0
def draw():

    for j in range(6):
        if j == 5:
            encoder = load_model("models/ae0.hdf5")
            encoder_output = encoder.predict(x_train)
        else:
            autoencoder_mse, encoder_output = Keras_AE_application.bulid_ae(
                x_train, original_dim, 40)

        ALL_minus1 = []
        TTUT = []
        TTTI = []
        TT = []
        TI = []
        ALL_not_minus1 = []

        for i in range(label.shape[0]):
            if label[i] == 0:
                ALL_minus1.append(encoder_output[i, 0:2])
            if label[i] == 1:
                TTTI.append(encoder_output[i, 0:2])
            if label[i] == 2:
                TI.append(encoder_output[i, 0:2])
            if label[i] == 3:
                TTUT.append(encoder_output[i, 0:2])
            if label[i] == 4:
                TT.append(encoder_output[i, 0:2])
            if label[i] == 5:
                ALL_not_minus1.append(encoder_output[i, 0:2])
        ALL_minus1 = np.array(ALL_minus1)
        TTTI = np.array(TTTI)
        TI = np.array(TI)
        TTUT = np.array(TTUT)
        TT = np.array(TT)
        ALL_not_minus1 = np.array(ALL_not_minus1)
        plt.subplot(3, 2, j + 1)
        if j == 0:
            plt.scatter(TTTI[:, 0],
                        TTTI[:, 1],
                        c='#31A97D',
                        s=3,
                        label='TI=-1,TT=-1,UT≠-1')
            plt.scatter(TI[:, 0],
                        TI[:, 1],
                        c='#3B4D86',
                        s=3,
                        label='TI=-1,TT≠-1,UT≠-1')
            plt.scatter(TTUT[:, 0],
                        TTUT[:, 1],
                        c='#1200FF',
                        s=3,
                        label='TI≠-1,TT=-1,UT=-1')
            plt.scatter(TT[:, 0],
                        TT[:, 1],
                        c='#F7E625',
                        s=3,
                        label='TI≠-1,TT=-1,UT≠-1')
            plt.scatter(ALL_not_minus1[:, 0],
                        ALL_not_minus1[:, 1],
                        c='#006400',
                        s=3,
                        label='TI≠-1,TT≠-1,UT≠-1')
            plt.scatter(ALL_minus1[:, 0],
                        ALL_minus1[:, 1],
                        c='#9F79EE',
                        s=3,
                        label='TI=-1,TT=-1,UT=-1')
            plt.legend(bbox_to_anchor=(0.00, 1.30),
                       loc=2,
                       ncol=3,
                       borderaxespad=0,
                       markerscale=4,
                       fontsize=12)
        else:
            plt.scatter(TTTI[:, 0], TTTI[:, 1], c='#31A97D', s=3)
            plt.scatter(TI[:, 0], TI[:, 1], c='#3B4D86', s=3)
            plt.scatter(TTUT[:, 0], TTUT[:, 1], c='#1200FF', s=3)
            plt.scatter(TT[:, 0], TT[:, 1], c='#F7E625', s=3)
            plt.scatter(ALL_not_minus1[:, 0],
                        ALL_not_minus1[:, 1],
                        c='#006400',
                        s=3)
            plt.scatter(ALL_minus1[:, 0], ALL_minus1[:, 1], c='#9F79EE', s=3)
        title = '(' + chr(ord('a') + j) + ')'
        plt.xlabel(title, fontsize=14)
        plt.tick_params(labelsize=12)  #设置坐标轴数字大小
        plt.subplots_adjust(wspace=0.2, hspace=0.4)  #调整子图间距
    plt.show()
fig, ax = plt.subplots(1, figsize=(6.40, 2.40), dpi=100)

x = [0.] * 32
x[0] = x[31] = 1.
x[18] = 2.

n = len(x)

lines = [
    ax.plot(range(n), x, 'bs-')[0],
    ax.text(0.32, -0.2, "Iteration #0", transform=ax.transAxes)
]

plt.tick_params(
    axis='x',  # changes apply to the x-axis
    which='both',  # both major and minor ticks are affected
    bottom=False,  # ticks along the bottom edge are off
    top=False,  # ticks along the top edge are off
    labelbottom=False)  # labels along the bottom edge are off
plt.tight_layout()

plt.draw()

#ax.grid()


def animate(iteration):
    global x, n
    if (0 == iteration):
        return lines

    for i in range(0, len(x)):
def fig_12(folder, dark_folder):
    intensity_arr, dark_arr = np.array([]), np.array([])
    files, dark_files = os.listdir(folder), os.listdir(dark_folder)

    filenum = 1000  #1000 files
    indexnum = 2048  #2048 pixels

    #this array will eventually contain an indexnum amount of rows;
    #where in each row, the varying intensities at a certain index are stored
    #rows correspond to pixel count
    intensity_arr = np.zeros(
        shape=(filenum,
               indexnum))  #an array that has filenum rows and indexnum cols
    for index, fil in enumerate(files[:filenum]):
        if fil == ".DS_Store":  #sometimes this appears in the folder and causes problems
            continue
        data = np.transpose(
            np.genfromtxt(folder + fil, skip_header=17, skip_footer=1))
        intensity_arr[index] = data[1][:indexnum]
    intensity_arr = np.transpose(intensity_arr)

    #likewise as intensity_arr, but accounting for the dark subtraction
    dark_arr = np.zeros(
        shape=(filenum,
               indexnum))  #an array that has filenum rows and indexnum cols
    for index, fil in enumerate(dark_files[:filenum]):
        if fil == ".DS_Store":
            continue
        data = np.transpose(
            np.genfromtxt(dark_folder + fil, skip_header=17, skip_footer=1))
        dark_arr[index] = data[1][:indexnum]
    dark_arr = np.transpose(dark_arr)

    #dark_corr_arr takes the average of the dark_arr at each pixel
    dark_corr_arr = np.array([])
    for elem in dark_arr:
        dark_corr_arr = np.append(dark_corr_arr, my_mean(elem))

    mean_arr = np.array([])
    variance_arr = np.array([])
    #get the mean (of the intensity_arr - dark subtraction) and the variance to plot
    for index, elem in enumerate(intensity_arr):
        mean, std = my_std(elem - dark_corr_arr[index])
        mean_arr, variance_arr = np.append(mean_arr, mean), np.append(
            variance_arr, std**2)

    linear = linleastsquares([mean_arr, variance_arr], 2)
    gain, ADU_0 = linear[1][0], linear[0][0]
    ideal_linear = linear[1] * mean_arr + linear[0]
    #this graph shows the correlation of how when the brightness increases, the variance increases too
    fig = plt.figure(figsize=(10, 5))
    plt.plot(mean_arr, variance_arr, 'o', linewidth=1)
    plt.plot(mean_arr,
             ideal_linear,
             'r-',
             label='gain = ' + str(gain) + '\nb = ' + str(ADU_0),
             linewidth=1.5)
    plt.xlabel("Mean, " + r'$\left(\overline{ADU - ADU_0}\right)$',
               fontsize=16)
    plt.ylabel("Variance, " + r'$\sigma^2$', fontsize=16)
    plt.tick_params(labelsize=14)
    plt.xlim([np.amin(mean_arr), np.amax(mean_arr)])
    plt.title('Correlation between Brightness and Variance', fontsize=18)
    #plt.yscale('log')
    plt.tight_layout()
    plt.legend(loc=2, fontsize=16)
    plt.xscale('log')
    plt.yscale('log')
    return fig
Example #47
0
def plot_ts(total_profiles_data, stations_to_plot, stations_range, lon,
            section_code, deployment_info):

    pres = []
    temp = []
    psal = []
    dens = []
    ptemp = []
    station_idx = []

    fig1 = plt.figure(figsize=(7.87402, 6.29921))
    ax1 = fig1.add_subplot(111)

    font_size = 8

    for n in range(0, stations_range):

        station = stations_to_plot[n]

        pres_station = total_profiles_data[station]['pres']
        temp_station = total_profiles_data[station]['temp1']
        psal_station = total_profiles_data[station]['psal1']

        RANGE = len(psal_station)
        station_idx_station = [lon[n]] * RANGE
        #pres.append(pres_station)
        #            temp.append(temp_station)
        #            psal.append(psal_station)

        dens_station, ptemp_station, si, ti, smin, smax, tmin, tmax = DataOps.calculate_dens_and_ptemp(
            psal_station, temp_station, pres_station)
        #            dens.append(dens_station)
        #            ptemp.append(ptemp_station)
        psal = np.concatenate((psal, psal_station), axis=0)
        ptemp = np.concatenate((ptemp, ptemp_station), axis=0)
        station_idx = np.concatenate((station_idx, station_idx_station),
                                     axis=0)

        if n == 0:
            levels = np.arange(dens_station.min(), dens_station.max(), 0.1)
            CS = plt.contour(si,
                             ti,
                             dens_station,
                             linewidths=0.05,
                             linestyle='--',
                             colors='k',
                             levels=levels)
            plt.clabel(CS, fontsize=4, inline=1, inline_spacing=1,
                       fmt='%1.1f')  # Label every second level

            ax1.grid(b=True, which='major', color='grey', linewidth=0.01)
            ax1.grid(b=True, which='minor', color='grey', linewidth=0.001)
            ax1.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
            ax1.xaxis.set_major_formatter(FormatStrFormatter('%.2f'))

            plt.xticks(np.arange(smin, smax, 0.1))
            plt.xticks(rotation=45)
            plt.yticks(np.arange(tmin + 1, tmax, 0.25))
            plt.tick_params(axis='both', which='major', labelsize=6)
            location_long_name = PlotSettings.set_location_long_name(
                section_code)
            plt.title(deployment_info['cruise_name'] + ' - Theta-S' + '  -  ' +
                      location_long_name,
                      fontsize=font_size)
            plt.xlabel('Salinity (PSU)', fontsize=font_size)
            plt.ylabel('Potential Temperature (deg C)', fontsize=font_size)

    plt.scatter(psal,
                ptemp,
                c=station_idx,
                s=20,
                edgecolor='black',
                linewidth='0.05')

    cbar = plt.colorbar()
    cbar.set_label('Longitude (deg E)', fontsize=font_size)
    cbar.ax.tick_params(labelsize=6)
    # set axes range
    plt.xlim(37.7, 38.7)
    plt.ylim(12.8, 15.2)
    # save figure
    figure_name = section_code + '_theta-s_diag.png'
    DataOps.save_figure(fig1, globfile.paths['output_figs_path'],
                        deployment_info['deployment_name'], figure_name)
#font
font1 = {'family' : 'sans-serif',
'weight' : 'light',
'size'   : list(figsize)[1]**1.6,
}

plt.bar(x, major, width=width, label=r'Average percentage of the dominant beliefs',fc = 'black')
for i in range(len(x)):
    x[i] = x[i] + width
plt.bar(x, num, width=width, label=r'Number of beliefs$(\times 10^{-1})$',tick_label = threshold,fc = 'grey')

plt.legend(prop=font1)


#设置坐标刻度值的大小以及刻度值的字体
plt.tick_params(labelsize=list(figsize)[1]**1.5)
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('serif') for label in labels]
#设置横纵坐标的名称以及对应字体格式
font2 = {'family' : 'sans-serif',#'sans-serif':['Computer Modern Sans serif'],#Times New Roman',
'weight' : 'light',
'size'   : list(figsize)[1]**1.6,
}
plt.xlabel('Threshold',font2)
plt.ylabel('Value',font2)
#plt.savefig('figure.pdf')
plt.savefig('figureserif.pdf')

plt.show()

'''
Example #49
0
                                    'test-name': 't-test',
                                    'better': better
                                },
                                ignore_index=True)

fig, ax = plt.subplots()

ttest_score = significance_test[significance_test['test-name'] == 't-test'][
    'better'].value_counts().nlargest(10).sort_values()
best_algo = ttest_score.reset_index().iloc[-1]['index']

ttest_score.plot(kind='bar')
# print(ttest_score.reset_index().iloc[-1]['index'])
dir = 'plots/scores/' + prefix + "/"
os.makedirs(dir, exist_ok=True)
plt.tick_params(axis='both', which='minor', labelsize=8)

labels = transform_labels(ax.get_xticklabels())
plt.xticks(ax.get_xticks(), labels, rotation=45)
plt.ylabel('Performance Score')
plt.savefig(dir + 't-test-hist.pdf', bbox_inches="tight")
plt.close()

# plt.show()

significance_result = pd.DataFrame({
    'benchmark': [],
    'algorithm': [],
    'budget': [],
    'performance': []
})
        # if not (i % 100):
        #     print('Solved at time ', str(i), ' after ', str(k), ' Newton iterations.')

np.save('data/eRT_04_alpha_02/u.npy', u)
fig1 = plt.figure(1)
plt.plot(t,
         u[0, :] * 10e-3,
         'black',
         label=r'$\displaystyle uninfected \; T \; cells$')
plt.grid()
plt.xlim((0, 400))
plt.xlabel(r'$\displaystyle time \; [days]$', labelpad=10, fontsize=18)
plt.ylabel(r'$\displaystyle cell \; concentration \; [cells/\mu l]$',
           labelpad=10,
           fontsize=18)
plt.tick_params(labelsize=16)
plt.tight_layout()
plt.show()
plt.savefig('images/eRT_0_alpha_0/treated_T.pdf', dpi=300, pad_inches=0.25)
# ttl1 = plt.title(r'$\displaystyle uninfected \;\; T \;\; cells$', fontsize = 15)
# ttl1.set_position([.5, 1.25])

# plt.subplot(3,1,2)
fig2 = plt.figure(2)
plt.yscale('log')
plt.plot(t, u[1, :], 'black', label='Ts')
plt.grid()
plt.xlim((0, 400))
# plt.legend()
plt.xlabel(r'$\displaystyle time \; [days]$', labelpad=10, fontsize=18)
plt.ylabel(r'$\displaystyle cell \; concentration \; [log_{10}(cells/ml^3)]$',
#%% Total MW per region

cmap = plt.get_cmap('plasma')
pv_region = dep_parc_prod.groupby(['REG_CODE']).P_MW.sum()
max_p = 2000
color = cmap(
    [pv_region[r] / max_p for r in polyreg.keys() for p in polyreg[r]])

ax = util.plot_polygons(util.list_polygons(polyreg, polyreg.keys()),
                        color=color)
tranches = np.arange(0, max_p + 0.001, (max_p) / 5)
labels = ['{:d} MW'.format(int(t)) for t in tranches]
palette = list(cmap([j / max_p for j in tranches]))
util.aspect_carte_france(ax, palette=palette, labels=labels)
plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False)

plt.gcf().set_size_inches(4.3, 4.06)
plt.title('(a) PV installed capacity', y=-0.1)
plt.tight_layout()
plt.savefig(r'c:\user\U546416\Pictures\France_PV\installedcap_fr_2021.png')
plt.savefig(r'c:\user\U546416\Pictures\France_PV\installedcap_fr_2021.pdf')

#%%
f, axs = plt.subplots(1, 3)
maxt = np.round(pv_reg.max() / 1000) * 1000
t**s = ['(a) Small-scale', '(b) Medium-scale', '(c) Large-scale']
for j, i in enumerate(['home_rooftop', 'commercial_rooftop', 'solar_farm']):
    cmap = plt.get_cmap('plasma')
    color = cmap(
        [pv_reg[r, i] / maxt for r in polyreg.keys() for p in polyreg[r]])
            linelist = f.readlines()
            f.close

            idf1 = float(linelist[0].split(',')[0])
            mota = float(linelist[0].split(',')[-1])

            results[t].append([idf1, mota])

    fontsize = 16
    tickfontsize = 12

    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')

    fig, ax1 = plt.subplots()
    plt.tick_params(labelsize=tickfontsize)

    # for t, data in results.items():
    #     sns.lineplot(x=30 // np.array(frame_skips), y=np.array(data)[:, 0], label=f'{t} - IDF1')
    #     sns.lineplot(x=30 // np.array(frame_skips),
    #                  y=np.array(data)[:, 1], label=f'{t} - MOTA')

    x = 30 // np.array(frame_skips)
    y = []
    linestyle = ['solid', 'dashed']
    for ls, (t, data) in zip(linestyle, results.items()):
        # y.append(np.array(data)[:, 0])
        # y.append(np.array(data)[:, 1])
        plt.plot(x, np.array(data)[:, 0], label='{} - IDF1'.format(t), ls=ls)
        plt.plot(x, np.array(data)[:, 1], label='{} - MOTA'.format(t), ls=ls)
Example #53
0
    t <= 0, t > 0, t > 1, t > 2, t > 3, t > 4, t > 5, t > 6, t > 7, t > 8,
    t > 9
]

lambdas = [
    lambda t: 1, lambda t: 1 - t, lambda t: t**2 / 2 - 2 * t + 3 / 2,
    lambda t: -t**3 / 6 + 3 * t**2 / 2 - 4 * t + 17 / 6,
    lambda t: t**4 / 24 - 2 * t**3 / 3 + 15 * t**2 / 4 - 17 * t / 2 + 149 / 24,
    lambda t: -t**5 / 120 + 5 * t**4 / 24 - 2 * t**3 + 109 * t**2 / 12 - 115 *
    t / 6 + 1769 / 120, lambda t: t**6 / 720 - t**5 / 20 + 35 * t**4 / 48 - 197
    * t**3 / 36 + 1061 * t**2 / 48 - 1085 * t / 24 + 26239 / 720,
    lambda t: -t**7 / 5040 + 7 * t**6 / 720 - t**5 / 5 + 107 * t**4 / 48 - 521
    * t**3 / 36 + 13081 * t**2 / 240 - 13201 * t / 120 + 463609 / 5040,
    lambda t: t**8 / 40320 - t**7 / 630 + 7 * t**6 / 160 - 487 * t**5 / 720 +
    3685 * t**4 / 576 - 27227 * t**3 / 720 + 39227 * t**2 / 288 - 39371 * t /
    144 + 3157891 / 13440, lambda t: -t**9 / 362880 + t**8 / 4480 - t**7 / 126
    + 701 * t**6 / 4320 - 1511 * t**5 / 720 + 51193 * t**4 / 2880 - 212753 * t
    **3 / 2160 + 1156699 * t**2 / 3360 - 1158379 * t / 1680 + 43896157 / 72576,
    lambda t: t**10 / 3628800 - t**9 / 36288 + 11 * t**8 / 8960 - 323 * t**7 /
    10080 + 1873 * t**6 / 3456 - 89269 * t**5 / 14400 + 279533 * t**4 / 5760 -
    7761511 * t**3 / 30240 + 23602499 * t**2 / 26880 - 23615939 * t / 13440 +
    5681592251 / 3628800
]

plt.plot(t, np.piecewise(t, conditions, lambdas))

plt.xlabel('t', fontsize=25)
plt.ylabel('x(t)', fontsize=25)
plt.tick_params(labelsize=25)
plt.show()
Example #54
0
print('y_test shape:', y_test.shape)

print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

from google.colab import drive
drive.mount('/content/drive')

plt.figure(figsize=(10, 10))
for i in range(25):
    rand_num = np.random.randint(0, 50000)
    cifar_img = plt.subplot(5, 5, i + 1)
    plt.imshow(x_train[rand_num])
    plt.xticks(color="None")
    plt.yticks(color="None")
    plt.tick_params(length=0)
    plt.title(y_train[rand_num])

plt.show()

# parameters for data
height = 224
width = 224
channels = 3
input_shape = (height, width, channels)
n_classes = 100

# parameters for optimizers
lr = 1e-3

# Parameters for training
df = pd.read_csv('2015_Green_Taxi_Trip_Data.csv')

#print df.describe()
# List unique values in the df['pickup_datetime'] column
# df.pickup_datetime.unique()
df = clean_data(df)

print "size before feature engineering:", df.shape
df = engineer_features(df)
print "size after feature engineering:", df.shape

## code to compare the two Tip_percentage identified groups
# split data in the two groups
df1 = df[df.Tip_percentage > 0]
df2 = df[df.Tip_percentage == 0]
"""
# generate histograms to compare
fs = 14 # fontsize
fig,ax=plt.subplots(2,1,figsize=(8,10))
plt.tick_params(labelsize=fs)
df.Tip_percentage.hist(bins = 20,normed=True,ax=ax[0])
ax[0].set_xlabel('Tip (%)', fontsize=fs)
ax[0].set_title('Distribution of Tip (%) - All transactions', fontsize=fs)
ax[0].set_ylabel('Group normed count', fontsize=fs)

plt.tick_params(labelsize=fs)
df1.Tip_percentage.hist(bins = 20,normed=True,ax=ax[1])
ax[1].set_xlabel('Tip (%)', fontsize=fs)
ax[1].set_title('Distribution of Tip (%) - Transaction with tips', fontsize=fs)
ax[1].set_ylabel('Group normed count', fontsize=fs)
plt.savefig('Question4_target_varc.jpeg',format='jpeg')
Example #56
0
rcParams.update({'font.size': 9})
fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 10
fig_size[1] = 6
df = pd.read_csv('by company.csv')
df.dropna()
df = df.iloc[::-1]
mycolors = [
    '#18008a', '#230f90', '#2f1e97', '#3b2d9e', '#4439a3', '#4f47aa',
    '#5a55b0', '#6563b7', '#7172bd', '#7c80c3', '#878eca', '#929cd0',
    '#9dabd7', '#a8b9dd', '#b3c7e4', '#bed5ea', '#cae4f1'
]
a = df.plot(x = 'Date', y=['BP, plc','EQT Corporation','Range Louisiana Operating, LLC',\
                            'Range Resources Corporation','Southwestern Energy Company',\
                            'Rice Energy, Inc.','Ascent Resources, LLC',\
                            'Gulfport Energy Corporation','Chesapeake Energy Corporation',\
                            'Anadarko Petroleum Corporation','Vine Oil & Gas, LP',\
                            'EXCO Resources, Inc.','GEP Haynesville, LLC',\
                            'Indigo Minerals, LLC','BHP Billiton, Limited',
                            'Exxon Mobil Corporation','Mewbourne Oil Company']
                            , kind="line", color=mycolors)

for line in a.lines:
    line.set_linewidth(1)
a.xaxis.grid(False)
a.legend(bbox_to_anchor=(1, 1.02), loc='best', ncol=1, fontsize='x-large')
plt.tick_params(axis='x', labelsize=8)
plt.xlabel("Date", color='black')
plt.ylabel("Rigs", color='black')
plt.savefig(path.basename(__file__) + ".png", bbox_inches='tight')
# plt.show()
Example #57
0
######################################################################
# Plot routine
######################################################################


print("***** plotting *****")

# Preparing plot
matplotlib.rcParams['xtick.major.pad'] = 15
matplotlib.rcParams['ytick.major.pad'] = 15

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

plt.minorticks_on()
plt.tick_params(labelsize=20, length=14, width=2)
plt.tick_params(which='minor', length=7, width=1.2)


# Getting the data
data = np.genfromtxt(output)

x = data[:,0]
y = data[:,1]
z = data[:,2]

# Substracting the -2LogL minimum to form Delta(-2LogL)
z2=[]
for z_el in z:
  z2.append(z_el-z.min())
Example #58
0
def create_plots(cwd=''):
    """
    Function to plot the results of the fault-tolerant Boussinesq system

    Args:
        cwd: current workign directory
    """

    ref = 'PFASST_BOUSSINESQ_stats_hf_NOFAULT_P16.npz'

    # noinspection PyShadowingBuiltins
    list = [('PFASST_BOUSSINESQ_stats_hf_SPREAD_P16.npz', 'SPREAD', '1-sided',
             'red', 's'),
            ('PFASST_BOUSSINESQ_stats_hf_INTERP_P16.npz', 'INTERP', '2-sided',
             'orange', 'o'),
            ('PFASST_BOUSSINESQ_stats_hf_SPREAD_PREDICT_P16.npz',
             'SPREAD_PREDICT', '1-sided+corr', 'blue', '^'),
            ('PFASST_BOUSSINESQ_stats_hf_INTERP_PREDICT_P16.npz',
             'INTERP_PREDICT', '2-sided+corr', 'green', 'd'),
            ('PFASST_BOUSSINESQ_stats_hf_NOFAULT_P16.npz', 'NOFAULT',
             'no fault', 'black', 'v')]

    nprocs = 16

    xtick_dist = 8

    minstep = 128
    maxstep = 176
    # minstep = 0
    # maxstep = 320

    nblocks = int(320 / nprocs)

    # maxiter = 14
    nsteps = 0
    maxiter = 0
    vmax = -99
    vmin = -8
    for file, strategy, label, color, marker in list:
        data = np.load(cwd + 'data/' + file)

        iter_count = data['iter_count'][minstep:maxstep]
        residual = data['residual'][:, minstep:maxstep]

        residual[residual <= 0] = 1E-99
        residual = np.log10(residual)
        vmax = max(vmax, int(np.amax(residual)))

        maxiter = max(maxiter, int(max(iter_count)))
        nsteps = max(nsteps, len(iter_count))

    print(vmin, vmax)
    data = np.load(cwd + 'data/' + ref)
    ref_iter_count = data['iter_count'][nprocs - 1::nprocs]

    rcParams['figure.figsize'] = 6.0, 2.5
    fig, ax = plt.subplots()

    plt.plot(range(nblocks), [0] * nblocks, 'k-', linewidth=2)

    ymin = 99
    ymax = 0
    for file, strategy, label, color, marker in list:

        if file is not ref:
            data = np.load(cwd + 'data/' + file)
            iter_count = data['iter_count'][nprocs - 1::nprocs]

            ymin = min(ymin, min(iter_count - ref_iter_count))
            ymax = max(ymax, max(iter_count - ref_iter_count))

            plt.plot(range(nblocks),
                     iter_count - ref_iter_count,
                     color=color,
                     label=label,
                     marker=marker,
                     linestyle='',
                     linewidth=lw,
                     markersize=ms)

    plt.xlabel('block', **axis_font)
    plt.ylabel('$K_\\mathrm{add}$', **axis_font)
    plt.title('ALL', **axis_font)
    plt.xlim(-1, nblocks)
    plt.ylim(-1 + ymin, ymax + 1)
    plt.legend(loc=2, numpoints=1, fontsize=fs)
    plt.tick_params(axis='both', which='major', labelsize=fs)
    ax.xaxis.labelpad = -0.5
    ax.yaxis.labelpad = -1
    # plt.tight_layout()

    fname = 'data/BOUSSINESQ_Kadd_vs_NOFAULT_hf.png'
    plt.savefig(fname, rasterized=True, bbox_inches='tight')
    # os.system('pdfcrop ' + fname + ' ' + fname)

    for file, strategy, label, color, marker in list:

        data = np.load(cwd + 'data/' + file)

        residual = data['residual'][:, minstep:maxstep]
        stats = data['hard_stats']

        residual[residual <= 0] = 1E-99
        residual = np.log10(residual)

        rcParams['figure.figsize'] = 6.0, 2.5
        fig, ax = plt.subplots()

        cmap = plt.get_cmap('Reds', vmax - vmin + 1)
        pcol = plt.pcolor(residual, cmap=cmap, vmin=vmin, vmax=vmax)
        pcol.set_edgecolor('face')

        if file is not ref:
            for item in stats:
                if item[0] in range(minstep, maxstep):
                    plt.text(item[0] + 0.5 - (maxstep - nsteps),
                             item[1] - 1 + 0.5,
                             'x',
                             horizontalalignment='center',
                             verticalalignment='center')

        plt.axis([0, nsteps, 0, maxiter])

        ticks = np.arange(vmin, vmax + 1)
        tickpos = np.linspace(ticks[0] + 0.5, ticks[-1] - 0.5, len(ticks))
        cax = plt.colorbar(pcol, ticks=tickpos, pad=0.02)
        cax.set_ticklabels(ticks)
        cax.ax.tick_params(labelsize=fs)

        cax.set_label('log10(residual)', **axis_font)
        plt.tick_params(axis='both', which='major', labelsize=fs)
        ax.xaxis.labelpad = -0.5
        ax.yaxis.labelpad = -0.5

        ax.set_xlabel('step', **axis_font)
        ax.set_ylabel('iteration', **axis_font)

        ax.set_yticks(np.arange(1, maxiter, 2) + 0.5, minor=False)
        ax.set_xticks(np.arange(0, nsteps, xtick_dist) + 0.5, minor=False)
        ax.set_yticklabels(np.arange(1, maxiter, 2) + 1, minor=False)
        ax.set_xticklabels(np.arange(minstep, maxstep, xtick_dist),
                           minor=False)

        plt.title(strategy)

        # plt.tight_layout()

        fname = 'data/BOUSSINESQ_steps_vs_iteration_hf_' + strategy + '.png'
        plt.savefig(fname, rasterized=True, bbox_inches='tight')
        # os.system('pdfcrop ' + fname + ' ' + fname)

        plt.close('all')
Example #59
0
# compute inter eletrcode distances in cm
inter_electrode_distance_xy = np.mean(distances_xy)
inter_electrode_distance_z = np.mean(distances_z)

print(" and contains {} x {} = {} points".format(n_points_xy, n_points_z, n_points))
print("Inter-electrode distance: {:.2f} mm x {:.2f} mm".format(10*inter_electrode_distance_xy, 10*inter_electrode_distance_z))

# create grid plot
n_plots_x = n_points_xy
n_plots_y = n_points_z
fig = plt.figure(figsize=(5,10))

# labels for entire plot
ax = fig.add_subplot(111)
plt.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off')
plt.grid(False)
plt.xlabel("cross-fiber direction")
plt.ylabel("fiber direction")  
plt.title("sEMG for {} x {} electrodes, t: [{}, {}]".format(n_points_xy, n_points_z, t_list[0], t_list[-1]))

# determine minimum and maximum overall values
emg_data = data[:,electrode_data_begin:]
minimum_value = np.min(emg_data)
maximum_value = np.max(emg_data)
print("EMG value range [mV]: [{},{}]".format(minimum_value, maximum_value))
print("time range [ms]: [{},{}]".format(t_list[0], t_list[-1]))
sampling_frequency = 1000*len(t_list) / (t_list[-1]-t_list[0])
print("sampling frequency [Hz]: {:.0f}".format(sampling_frequency))

# loop over sub plots
Example #60
0
import csv

open_file = open("sitka_weather_07-2018_simple.csv", "r")

csv_file = csv.reader(open_file, delimiter = ",")

header_row = next(csv_file)
'''
print(header_row)

for index, column_header in enumerate(header_row):
    print(index, column_header)
'''
highs = []

for row in csv_file:
    highs.append(int(row[5]))

print(highs)

import matplotlib.pyplot as plt

plt.plot(highs, c= "red")

plt.title("Daily High Temp, July 2018", fontsize = 16)
plt.xlabel("")
plt.ylabel("Temperature (F)", fontsize = 16)
plt.tick_params(axis = "both", which = "major", labelsize = 16)

plt.show()