Example #1
0
def plot_decision_regions(X, y, classifier, resolution=0.02):
    # prepare marker and color map
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # plot decision regions
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    # generate grid point
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                           np.arange(x2_min, x2_max, resolution))
    # translate features into array and predict
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    # translate result to grid point
    Z = Z.reshape(xx1.shape)
    # plot contour line of grid point
    plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)

    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

    # plot sample by each class
    for idx, cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=cmap(idx),
                    marker=markers[idx], label=cl)
def histogram_rgb():
    img = cv2.imread("2.jpeg", )
    cv2.imshow("image", img)
    color = ('r', 'g', 'b')
    for channel, c in enumerate(color):
        hist = cv2.calcHist([img], [channel], None, [256], [0, 256])
        plt.subplot(1, 3, channel + 1)
        plt.title('Channel {}, color {} '.format(channel, c))
        plt.plot(hist, color=c)
        plt.xlim([0, 256])

    plt.show()
    key = cv2.waitKey(0)
def test_results():
    # testing and plotting curtailment results to compare to aviva's plots

    (plantType, hr, fuelAndCoalType, coolType, fgdType, state,
     capac) = getKeyCurtailParams(gen, genFleet)
    coeffs = getCoeffsForGenOrTech(plantType, coolType, genparam.ptCurtailed,
                                   regCoeffs, genparam.coolDesignT)

    x = np.arange(start=70, stop=110.1, step=0.1)
    y = np.arange(start=20, stop=110.1, step=0.1)

    xy = np.array(np.meshgrid(x, y)).reshape(2, x.shape[0] * y.shape[0]).T

    metAndWaterData = pd.DataFrame({
        'airF': xy[:, 0],
        'rh': xy[:, 1],
        'airF:rh': xy[:, 0] * xy[:, 1]
    })

    hourlyCurtailments = runCurtailRegression(metAndWaterData, coeffs,
                                              genparam.incCurtailments,
                                              plantType, coolType,
                                              genparam.ptCurtailed)

    xx, yy = np.meshgrid(x, y)
    zz = np.array(hourlyCurtailments).reshape(xx.shape)

    fig, ax = plt.subplots(1)

    N = 10
    base = plt.cm.get_cmap(plt.get_cmap('YlGn'))
    color_list = base(np.linspace(0, 1, N))
    cmap_name = base.name + str(N)
    my_map = base.from_list(cmap_name, color_list, N)

    bins = np.concatenate(([-np.inf], np.arange(start=0.1, stop=1,
                                                step=0.1), [np.inf]))
    values = np.digitize(zz, bins)

    im = ax.pcolormesh(xx, yy, values, cmap=my_map)

    plt.xlim(70, 110)
    plt.ylim(20, 100)

    cbar = fig.colorbar(im, orientation='vertical')
    cbar.set_ticks([])
    for j in np.arange(N + 1, step=2):
        cbar.ax.text(1, j / N, j / N, ha='left', va='center')

    plt.savefig('./example.png')
    plt.close(fig)
def plot_winavg_vectors(data, attribute, start=0, duration=SIM_TIME, win=100):
    sel = data[data.name == attribute]
    index_malus = 0

    for row in sel.itertuples():
        pprint.pprint(row)
        plt.plot(row.time,
                 winavg(row.value, win),
                 label=f"{malus[index_malus]}")
        index_malus = index_malus + 1

    plt.title("responseTime")
    plt.xlim(start, duration)
    return
Example #5
0
    def boton_alcance_horizontalf(self):

        # __Variables necesarias para conseguir R (alcance horizontal)__ #
        xi = int(self.entrada_posicion_x0.get())
        yi = int(self.entrada_posicion_y0.get())
        v0 = int(self.entrada_Rapidez_inicial.get())
        angulo0 = math.radians(int(self.entrada_angulo_inicial.get()))
        coseno = math.cos(angulo0)
        seno = math.sin(angulo0)
        vxo = v0 * coseno
        vyo = v0 * seno
        g = 9.8
        altura = int(self.entrada_posicion_y0.get()) + (((v0 * seno)**2) /
                                                        (2 * g))
        imp = (g * yi / math.pow(v0, 2))
        time = (v0 / g) * (seno + math.sqrt(math.pow(seno, 2) + 2 * imp))

        # __Ecuacion dividida en 4 partes para conseguir R__ #
        R1 = (math.pow(v0, 2) * math.sin(2 * angulo0)) / (2 * g)
        R2 = (v0 * coseno) / g
        R3 = np.sqrt((math.pow((v0 * seno), 2)) + (2 * yi * g))
        R = xi + R1 + R2 * R3

        imprimir = (
            "{0:.2f}".format(R)
        )  # Imprimir guarda el resultado final (R) y lo deja con solo dos decimales
        print("R = ", R)  # print de control

        # __Estetica de la grafica__ #
        mpl.suptitle('Alcance Horizontal:', fontsize=22)
        mpl.subplots_adjust(top=0.80)
        mpl.title(R, fontsize=18, color='C3')
        mpl.xlim(0, R + 2)
        mpl.ylim(-0.03, altura + 2)
        mpl.xlabel("X(m)")
        mpl.ylabel("Y(m)")

        # __Dibujado de la curva__ #
        x = np.arange(0, time, 0.001)
        c_y = yi + vyo * x + (
            1 / 2) * -9.8 * x**2  # Ecuacion de lanzamiento de proyectil
        c_x = xi + vxo * x + (
            1 / 2) * 0 * x**2  # Ecuacion de lanzamiento de proyectil
        mpl.plot(c_x, c_y, "-")  # lanzamiento completo
        mpl.plot(R, 0, "ro")
        mpl.show()
        pass
def plotFeatImportance(pathOut,imp,oob,oos,method,tag=0,simNum=0,**kargs):
    # plot mean imp bars with std
    mpl.figure(figsize=(10,imp.shape[0]/5.))
    imp=imp.sort_values('mean',ascending=True)
    ax=imp['mean'].plot(kind='barh',color='b',alpha=0.25,xerr=imp['std'],
                        error_kw={'ecolor':'r'})
    if method=='MDI':
        mpl.xlim([0,imp.sum(axis=1).max()])
        mpl.axvline(1./imp.shape[0],lw=1.,color='r',ls='dotted')
    ax.get_yaxis().set_visible(False)
    for i,j in zip(ax.patches,imp.index):
        ax.text(i.get_width()/2, i.get_y()+i.get_height()/2,
                j,ha='center',va='center',color='k')
    mpl.title('tag='+tag+' | simNUm='+str(simNum)+' | oob='+str(round(oob,4))+' | oos='+str(round(oos,4)))
    mpl.savefig(pathOut+'featImportance_'+str(simNum)+'.png',dpi=100)
    mpl.clf();mpl.close()
    return
Example #7
0
def plot_roc_curve(fpr, tpr, roc_auc, title='ROC curve'):
    plt.figure()
    lw = 2
    colors = cycle(['darkorange', 'blue', 'red', 'green', 'black', 'purple',
                   'yellow'])
    for i, color in zip(range(len(fpr), colors)):
        plt.plot(fpr[i], tpr[i], color=color, lw=lw,
                 label='ROC area {0:.4f}'.format(roc_auc[i]))
    # plt.plot(fpr, tpr, color='darkorange', lw=lw,
    #          label='ROC area under curve = {}'.format(roc_auc))
    plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.title(title)
    plt.xlabel('False positive rate')
    plt.ylabel('True positive rate')
    plt.legend(loc='lower right')
    plt.show()
Example #8
0
def blca(datafile,numprocs): 
	#run c++ blocking routine, saves txt data file with blocking data
	os.system("make --silent")
	os.system("mpirun -n %i blocking.out 100 3000 2 %i %s"%(nprocs,numprocs,datafile))#VMC
#os.system("mpirun -n %i blocking.out 5000 100 20000 %i %s"%(nprocs,numprocs,datafile))#DMC
	#read txt file and save plot
	data = np.genfromtxt(fname=datafile+'.txt')
	fig=plt.figure()
	plt.plot(data[:,0],data[:,2],'k+')
	plt.xlabel(r'$\tau_{trial}$', size=20)
	plt.ylabel(r'$\epsilon$', size=20)
	plt.xlim(np.min(data[:,0]),np.max(data[:,0]))
	plt.ylim(np.min(data[:,2]),np.max(data[:,2]))
	fig.savefig(datafile+'.eps',format='eps')
	#open plot if -p in argv
	if plot_res:
		os.system('evince %s%s '%(datafile+'.eps','&'))
	print("plot saved : %s"%(datafile+'.eps'))
Example #9
0
def plot_roc(y_true: List[str], y_score: List[float]) -> None:
    """Plot a ROC curve for these results"""

    fpr, tpr, threshold = roc_curve(y_true, y_score, pos_label="target")
    fnr = 1 - tpr
    EER = fpr[np.nanargmin(np.absolute((fnr - fpr)))]
    print("EER: {}%".format(EER * 100))

    plt.figure()
    lw = 2
    plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve')
    plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver operating characteristic example')
    plt.legend(loc="lower right")
    plt.show()
Example #10
0
def blca(datafile, numprocs):
    #run c++ blocking routine, saves txt data file with blocking data
    os.system("make --silent")
    os.system("mpirun -n %i blocking.out 100 3000 2 %i %s" %
              (nprocs, numprocs, datafile))  #VMC
    #os.system("mpirun -n %i blocking.out 5000 100 20000 %i %s"%(nprocs,numprocs,datafile))#DMC
    #read txt file and save plot
    data = np.genfromtxt(fname=datafile + '.txt')
    fig = plt.figure()
    plt.plot(data[:, 0], data[:, 2], 'k+')
    plt.xlabel(r'$\tau_{trial}$', size=20)
    plt.ylabel(r'$\epsilon$', size=20)
    plt.xlim(np.min(data[:, 0]), np.max(data[:, 0]))
    plt.ylim(np.min(data[:, 2]), np.max(data[:, 2]))
    fig.savefig(datafile + '.eps', format='eps')
    #open plot if -p in argv
    if plot_res:
        os.system('evince %s%s ' % (datafile + '.eps', '&'))
    print("plot saved : %s" % (datafile + '.eps'))
Example #11
0
def visual_importnance(X, forest):
    importances = forest.feature_importances_
    std = np.std([tree.feature_importances_ for tree in forest.estimators_],
                 axis=0)
    indices = np.argsort(importances)[::-1]

    # Print the feature ranking
    print("Feature ranking:")

    for f in range(X.shape[1]):
        print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))

    # Plot the feature importances of the forest
    plt.figure()
    plt.title("Feature importances")
    plt.bar(range(X.shape[1]), importances[indices],
            color="r", yerr=std[indices], align="center")
    plt.xticks(range(X.shape[1]), indices)
    plt.xlim([-1, X.shape[1]])
    plt.show()
Example #12
0
def RysujGeom(x_range, WEZLY, ELEMENTY, types):

    plt.plot(x_range[0], 0, '*')  #x_range[0]
    plt.plot(x_range[1], 0, '*')  #x_range[1]
    plt.plot(x_range, [0, 0])
    plt.plot(WEZLY, np.zeros(len(WEZLY)), '*')

    plt.text(x_range[0] - 0.15, 0, types[0])
    plt.text(x_range[1] + 0.15, 0, types[1])

    for i in range(0, len(WEZLY)):
        plt.text(WEZLY[i] - 0.03, 0.01, str(WEZLY[i]))
        plt.text(WEZLY[i] - 0.05, -0.05, str(i + 1))

    for i in range(0, len(WEZLY) - 1):
        print((WEZLY[i] - WEZLY[i + 1]) / 2)
        plt.text(WEZLY[i] / 2 + WEZLY[i + 1] / 2, 0.05, str(i + 1))

    plt.xlim([x_range[0] - 0.3, x_range[1] + 0.3])
    plt.ylim([-0.2, 0.42])
def plot_mean_vectors(data,
                      attribute,
                      start=WARMUP_PERIOD,
                      duration=SIM_TIME,
                      iterations=None):
    if iterations is None:
        iterations = [0]

    sel = data[data.name == attribute]

    # plot a mean vector for each iteration
    for i in iterations:
        tmp = sel[sel.run == i]

        for row in tmp.itertuples():
            plt.plot(row.time, running_avg(row.value))

    plt.title("responseTime")
    plt.xlim(start, duration)
    plt.show()
    return
    def plot_trial_avg_data_with_stds(self, neuron_ind, var_level):

        neuron_i_data_by_trial = self.by_trial_IT_Neural_Data_objmeans_sorted_by_category[var_level][:, :, neuron_ind]
        neuron_i_data_trial_mean = neuron_i_data_by_trial.mean(1)
        neuron_i_data_trial_std = neuron_i_data_by_trial.std(1)
        minval = neuron_i_data_trial_mean.min()
        maxval = neuron_i_data_trial_mean.max()
        plt.plot(neuron_i_data_trial_mean)
        plt.fill_between(np.arange(64), minval, maxval, 
                         where=(np.arange(64) / 8) % 2, color='k', alpha=0.2)

        plt.fill_between(np.arange(64), 
                         neuron_i_data_trial_mean - neuron_i_data_trial_std,
                         neuron_i_data_trial_mean + neuron_i_data_trial_std,
                         color='b', alpha=0.2)

        plt.xticks(np.arange(0, 64, 8) + 4, self.unique_categories, rotation=30);
        plt.ylabel('Neural Responses')
        plt.ylim(minval, maxval)
        plt.title('Responses for neuron %d Variation %s images' % (neuron_ind, var_level))
        plt.xlim(0, 64)
def plot_mean_vectors_datalink(data,
                               prefix,
                               start=0,
                               duration=SIM_TIME,
                               iterations=None,
                               datalinks=range(0, NUM_DATA_LINK)):
    if iterations is None:
        iterations = [0]

    sel = data[data.name.str.startswith(prefix + '-')]

    for d in datalinks:
        usr = sel[sel.name == prefix + "-" + str(d)]
        for i in iterations:
            tmp = usr[(usr.run == i)]
            for row in tmp.itertuples():
                plt.plot(row.time, running_avg(row.value))

    # plot the data
    plt.xlim(start, duration)
    plt.show()
    return
Example #16
0
def udaljenost_tocke(x1,y1,x2,y2,r):
    plt.xlim([0,10])
    plt.ylim([0,10])
    kruznica = plt.Circle((x2,y2),r,color='r')
    plt.gca().add_artist(kruznica)
    plt.plot(x1,y1, 'bo')
    x = (x1-x2)**2 + (y1-y2)**2
    d = sqrt(x)
    nacin = int(input('Unesi 1 za prikaz slike, 2 za spremanje'))
    if znak ==1:
        plt.show()
    elif znak ==2:
        naziv = input('Unesite naziv slike:')
        plt.savefig(f'{naziv}.pdf')

    epsilon = 0.01
    if d < r:
        print(f'Točka je unutar kružnice, a udaljenost je {d}.')
    elif r-epsilon < d < r+epsilon:
        print(f'Točka se nalazi na kružnici.')
    else:
        print(f'Točka je izvan kružnice, a udaljenost je {d}.')
Example #17
0
    def plot_board(self):
        X = self.X
        fig = plt.figure(figsize=(5, 5))
        plt.xlim(-1, 1)
        plt.ylim(-1, 1)

        if self.mu and self.clusters:
            mu = self.mu
            clus = self.clusters
            K = self.K

            for m, clu in clus.items():
                cs = cm.spectral(1. * m / self.K)
                plt.plot(mu[m][0],
                         mu[m][1],
                         'o',
                         marker='*',
                         markersize=12,
                         color=cs)
                plt.plot(zip(*clus[m])[0],
                         zip(*clus[m])[1],
                         '.',
                         markersize=8,
                         color=cs,
                         alpha=0.5)

        else:
            plt.plot(zip(*X)[0], zip(*X)[1], '.', alpha=0.5)

        if self.method == '++':
            tit = 'K-means++'
        else:
            tit = 'K-means with random initialization'

        pars = 'N=%s, K=%s' % (str(self.N), str(self.K))
        plt.title('\n'.join([pars, tit]), fontsize=16)
        plt.savefig('kpp_N%s_K%s.png' % (str(self.N), str(self.K)),
                    bbox_inches='tight',
                    dpi=200)
Example #18
0
def make_bar_graph(data=housing):
    '''

    :param data:
    :return:
    '''
    data = data
    mp.figure('Bar', facecolor='lightgray')
    mp.title('Bar', fontsize=20)
    gs = mg.GridSpec(3, 4)
    i, j = 0, 0
    for column in housing.columns:
        # 创建子图
        mp.subplot(gs[i, j])
        # 在图形内部添加文字,设置位置,内容,对齐方式,字号,颜色,透明度
        mp.text(0.5, 0.5, str(i) + '+' +  str(j), ha='center', va='center', size=35, color='red', alpha=0.5)
        # 删除边界刻度
        mp.xticks(())
        mp.yticks(())
        # 绘制柱状图
        single_data = housing[column]
        min_data, max_data = min(single_data), max(single_data)
        mp.xlim(min(min_data, max_data))
        step = (max_data - min_data) / 10
        for x in range(min_data, max_data, step):
            sum_num = sum(x <= single_data <= x + step)
            y.append(sum_num)
        x = np.range(len(y))
        mp.bar(x, y, 0.4, color='dodgerblue', label=column, alpha=0.75)
        # 调整子图位置
        j += 1
        j = j % 4
        i = i + j // 4
            
    # 改变布局形式,改为紧凑布局
    mp.tight_layout()
    pass
Example #19
0
def show_perceptron(X, Y, w, b):
    """Present the current state of the perceptron algorithm
    where X (sequence of sequences) isthe data
    Y - the labels
    w - the candidate seperator
    b- the seprator bias
    Works only for 2D data - X assumed to be sequence of sequences of size 2
    """
    if len(X) != 2 or len(Y) != 2 or len(w) != 2:
        print("Works only for 2d data!")
        return

    X = np.array(X)
    Y = np.array(Y)
    w = np.array(w)
    ploty.plot(X[Y == 1, 0],
               X[Y == 1, 1],
               'bD',
               markersize=10,
               linestyle='None',
               linewidth=3)
    ploty.plot(X[Y == -1, 0],
               X[Y == -1, 1],
               'ro',
               markersize=10,
               linestyle='None',
               linewidth=3)

    minx = min(X[:, 0]) - abs(min(X[:, 0])) * 0.2
    maxx = max(X[:, 0]) + abs(max(X[:, 0])) * 0.2
    miny = min(X[:, 1]) - abs(min(X[:, 1])) * 0.2
    maxy = max(X[:, 1]) + abs(max(X[:, 1])) * 0.2
    ploty.xlim([minx, maxx])
    ploty.ylim([miny, maxy])
    A = np.arange(minx, maxx, 0.01)
    if w[0] == 0 and w[1] == 0:
        ploty.plot(0, b, '.k', linewidth=2)
        ploty.xlim(min(minx, -0.1), max(maxx, 0.1))
        ploty.ylim(min(miny, b - 0.1), max(maxy, b + 0.1))
    elif w[1] == 0:
        B = np.arange(miny - abs(miny) * 0.2, maxy + abs(maxy) * 0.2, 0.01)
        b = b / w[0]
        ploty.plot([b] * len(B), B, 'k', linewidth=2)
        ploty.xlim(min(minx, b - 0.1), max(maxx, b + 0.1))
    else:
        l = b / w[1] - (w[0] / w[1]) * A
        ploty.plot(A, l, 'k', linewidth=2)
        ploty.ylim(min(miny, min(l)), max(maxy, max(l)))
    ploty.show()
Example #20
0
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test  = diabetes.target[-20:]


regr = linear_model.LinearRegression()
regr.fit(diabetes_X_train, diabetes_y_train)

# >> LinearRegression(copy_X=True, fit_intercept=True, normalize=False)
print regr.coef_

# The mean square error
np.mean((regr.predict(diabetes_X_test)-diabetes_y_test)**2)

# Explained variance score: 1 is perfect prediction
# and 0 means that there is no linear relationship
# between X and Y.
regr.score(diabetes_X_test, diabetes_y_test) 

# Plot results

pl.clf()          # Clear plots

pl.plot(diabetes_X_test, regr.fit(diabetes_X_train, diabetes_y_train));

pl.title('Linear regression of sample diabetes data\n'
         'Centroids are marked with white cross')
pl.xlim(x_min, x_max)
pl.ylim(y_min, y_max)
pl.xticks(())
pl.yticks(())
pl.show()
Example #21
0
def plotFeatureArrays(featureVecs,
                      array_shape,
                      n_figs=10,
                      tiled=True,
                      tiles_shape=(2, 5),
                      tile_psn=(.1, .125, .4, .4),
                      xlims=None,
                      ylims=None,
                      titles=None,
                      xlabel=None,
                      ylabel=None,
                      noise_floor=None,
                      extent=None,
                      origin=None,
                      colorbar=True):

    n_samples = featureVecs.shape[0]

    if tiled:
        sample_idxs = np.array(random.sample(range(n_samples)),
                               np.prod(tiles_shape)).reshape(tiles_shape)

        plt.figure()

        for r in range(tiles_shape[0]):
            for c in range(tiles_shape[1]):
                idx = sample_idxs[r, c]
                arr = featureVecs[idx, :].reshape(array_shape)

                # set signal limits
                maxSig = arr.max()
                if noise_floor is not None:
                    minSig = magSig - noise_floor
                    arr[arr < minSig] = minSig
                minSig = arr.min()

                left = tile_psn[0] * (c + 1) + tile_psn[2] * c
                bottom = tile_psn[1] * (r + 1) + tile_psn[3] * r

                plt.axes((left, bottom, tile_psn[2], tile_psn[3]))

                plt.imshow(arr,
                           extent=extent,
                           aspect='auto',
                           interpolation='nearest',
                           origin=origin,
                           cmap='binary',
                           vmin=minSig,
                           vmax=maxSig)

                if colorbar:
                    plt.colorbar()

                if xlims is not None:
                    plt.xlim(xlims)

                if ylims is not None:
                    plt.ylim(ylims)

                if xlabel is not None and r == 0:
                    plt.xlabel(xlabel)
                else:
                    plt.xticks([])

                if ylabel is not None and c == 0:
                    plt.ylabel(ylabel)
                else:
                    plt.yticks([])

                if titles is not None:
                    plt.title(title[idx])

                plt.show()

    else:
        sample_idxs = np.array(random.sample(range(n_samples)), n_figs)

        for idx in sample_idxs:
            arr = featureVecs[idx, :].reshape(array_shape)

            # set signal limits
            maxSig = arr.max()
            if noise_floor is not None:
                minSig = magSig - noise_floor
                arr[arr < minSig] = minSig
            minSig = arr.min()

            plt.figure()
            plt.axes(tile_psn)

            plt.imshow(arr,
                       extent=extent,
                       aspect='auto',
                       interpolation='nearest',
                       origin=origin,
                       cmap='binary',
                       vmin=minSig,
                       vmax=maxSig)

            if colorbar:
                plt.colorbar()

            if xlims is not None:
                plt.xlim(xlims)

            if ylims is not None:
                plt.ylim(ylims)

            if xlabel is not None and r == 0:
                plt.xlabel(xlabel)
            else:
                plt.xticks([])

            if ylabel is not None and c == 0:
                plt.ylabel(ylabel)
            else:
                plt.yticks([])

            if titles is not None:
                plt.title(title[idx])

            plt.show()
Example #22
0
def create_figure_surface(figid, aspect, xx, yy, cmin, cmax, levels, slices, v3d):
    ''' creates a plot of the surface of a tracer data
    Parameters
    ----------
    figid : int  
            id of figure
    aspect: float
            aspect ratio of figure
    xx    : array 
            scale of x axis
    yy    : array 
            scale of y axis     
    cmin,cmax : array
                minimum and maxminm of the color range
    levels : array
            range of contourlines
    slices : array
            location of slices
    v3d    : vector data in geometry format
    Returns
    -------
    plot :  of surface data
    '''
    # prepare matplotlib
    import matplotlib
    matplotlib.rc("font",**{"family":"sans-serif"})
    matplotlib.rc("text", usetex=True)
    #matplotlib.use("PDF")
    import matplotlib.pyplot as plt
    # basemap
    from mpl_toolkits.basemap import Basemap
    # numpy
    import numpy as np

    # data
    vv = v3d[0,:,:,0]
    # shift
    vv = np.roll(vv, 64, axis=1)

    # plot surface
    plt.figure(figid)
    # colormap
    cmap = plt.cm.bone_r
    # contour fill
    p1 = plt.contourf(xx, yy, vv, cmap=cmap, levels=levels, origin="lower")#, hold="on")
    plt.clim(cmin, cmax)
    # contour lines
    p2 = plt.contour(xx, yy, vv, levels=levels, linewidths = (1,), colors="k")#, hold="on")
    plt.clabel(p2, fmt = "%2.1f", colors = "k", fontsize = 14)
    #plt.colorbar(p2,shrink=0.8, extend='both')
    # slices
    #s1 = xx[np.mod(slices[0]+64, 128)]
    #s2 = xx[np.mod(slices[1]+64, 128)]
    #s3 = xx[np.mod(slices[2]+64, 128)]
#    print s1, s2, s3
    #plt.vlines([s1, s2, s3], -90, 90, color='k', linestyles='--')
    # set aspect ratio of axes
    plt.gca().set_aspect(aspect)

    # basemap
    m = Basemap(projection="cyl")
    m.drawcoastlines(linewidth = 0.5)

    # xticks
    plt.xticks(range(-180, 181, 45), range(-180, 181, 45))
    plt.xlim([-180, 180])
    plt.xlabel("Longitude [degrees]", labelpad=8)
    # yticks
    plt.yticks(range(-90, 91, 30), range(-90, 91, 30))
    plt.ylim([-90, 90])
    plt.ylabel("Latitude [degrees]")


    # write to file
    plt.savefig("solution-surface", bbox_inches="tight")
    plt.show()
Example #23
0
        else: # violated
            self.pt_test.set_color('r')

        # n_prev@(xp-xp)<=b ->>> penality <= 0
        obs_con_penality= ds
        self.txt3.set_text('n_prev@(xp-xp)-b = %1.2f' % (obs_con_penality))


center = np.array([0.1,-0.15,0.])
widths_vec = np.ones(3)
obs = PolygonalObstacle(center, widths_vec)

fig, ax = plt.subplots()

plot_rectangle(ax, center[idx], widths_vec[idx])
plt.xlim([-1.5*widths_vec[idx[0]],2.5*widths_vec[idx[0]]])
plt.ylim([-1.5*widths_vec[idx[1]],2.5*widths_vec[idx[1]]])

if idx[0] == 0:
	plt.xlabel('x')
elif idx[0] == 1:
	plt.xlabel('y')
else:
	plt.xlabel('z')
if idx[1] == 0:
	plt.ylabel('x')
elif idx[1] == 1:
	plt.ylabel('y')
else:
	plt.ylabel('z')
Example #24
0
print (dado)


# In[4]:


date = pd.date_range('1998-01-01','2019-05-01', freq = 'M').strftime('%m-%Y') 


# In[5]:


plt.figure(figsize = (25,12))
plt.plot (pr,'-b')
plt.xticks(range(0, pr.size, 4), date[::4], rotation = 60)
plt.xlim([range(0, pr.size)[0],range(0, pr.size)[-1]])


# #### b) Quais os problemas que voce indentificou na apresentação do seu dado. Como o gráfico poderia ter sua apresentação melhorada? 

# In[6]:


str = 'o gráfico fica poluido, poderia melhorar trabalhando um intervalo maior'


# #### 2) Com o mesmo arquivo, calcule a média de precipitação para cada ano. Construa um gráfico de barras com a média de cada ano.

# In[7]:

Example #25
0
x_set, y_set = train_x, train_y
X1, X2 = np.meshgrid(
    np.arange(start=x_set[:, 0].min() - 1,
              stop=x_set[:, 0].max() + 1,
              step=0.01),
    np.arange(start=x_set[:, 1].min() - 1,
              stop=x_set[:, 1].max() + 1,
              step=0.01))
plt.countourf(
    X1,
    X2,
    cls_svc.predict(np.array([X1.ravel, X2.ravel()]).T).reshape(X1.shape),
    alpha=0.75,
    cmap=ListedColormap(("red", "green"))
)  ###### countourf- logistic regression ne devide kare  && ravel--- midpoint kadhwa
plt.xlim(X1.min(), X1.max())  #### limit banavi
plt.ylim(X2.min(), X2.max())

for i, j in enumerate(np.unique(y_set)):
    plt.scatter(x_set[y_set == j, 0],
                x_set[y_set == j, 1],
                c=ListedColormap(('red', 'green'))(i),
                label=j)

plt.title("SVM training set")
plt.xlabel("age")
plt.ylabel("estimated salary")
plt.legend()
plt.show()

######### plotting testing setsss
Example #26
0
# In[90]:

fig = plt.figure()
nPC = range(1, maxNumPC + 1)
maker = ['x', 's', '^', '+', 'o', 'D']
for i in [5, 2, 4, 3, 1, 0]:
    expt, m, p = exptList[i]
    plt.semilogy(accList[expt],
                 timeList[expt],
                 '-' + maker[2 * m + p],
                 label="{} {}".format(modelList[m], policyList[p]))
plt.ylabel("Time in second")
plt.xlabel("Accuracy (%)")
plt.title("Accuracy vs time for different classifiers")
plt.xlim([0, 100])
plt.grid("on")
plt.legend(loc="best")
fig.set_size_inches(10, 6)
fName = os.path.join(pDir, 'accuracy_time_n{}_{}.png'.format(n, rev))
savefig(fName, bbox_inches='tight')
plt.show()

# In[83]:

fig = plt.figure()
nPC = range(1, maxNumPC + 1)
maker = ['x', 's', '^', '+', 'o', 'D']
for i in [5, 2, 4, 3, 1, 0]:
    expt, m, p = exptList[i]
    plt.semilogy(accList[expt],
Example #27
0
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 23 11:07:06 2017

@author: Paige
"""

import matplotlib as plt
import numpy as np


x = np.linspace(-10, 10, 400)
cos = np.cos(x)
sin = np.sin(x)
plt.plot(x, cos, "r", label="cos(x)")        # r for red line
plt.plot(x, sin, "b--", label="sin(x)")      # b-- for blue dashed line
# colors include red(r), green(g), yellow(y), blue(b), cyan(c),
# magenta(m), black(k), white(w)
# line styles include solid line("-"), dashed line("--"),
# solid line("-"), square("s"), dots("o"), smaller dots(".")
plt.xlim(-10, 10)
plt.legend()
plt.xlabel("x")
plt.title("Trigonometric Functions")
plt.ylabel("cos(x) or sin(x)")
# plt.savefig("1-23-2017.png")
plt.show()
Example #28
0
            model.predict(X0[:1]),
            marker='o',
            s=300,
            c='r',
            lw=5,
            alpha=0.5)
plt.plot(xx, model.predict(xx[:, np.newaxis]) > 0.5, lw=2)
plt.scatter(X0[0],
            model.predict_proba(X0[:1])[0][1],
            marker='x',
            s=300,
            c='r',
            lw=5,
            alpha=0.5)
plt.axvline(X0[0], c='r', lw=2, alpha=0.5)
plt.xlim(-3, 3)
plt.subplot(212)
plt.bar(model.classes_, model.predict_proba(X0[:1])[0], align="center")
plt.xlim(-1, 2)
plt.gca().xaxis.grid(False)
plt.xticks(model.classes_)
plt.title("conditional probability")
plt.tight_layout()
plt.show()

from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.cross_validation import train_test_split
iris = load_iris()
X = iris.data[:, [2, 3]]
y = iris.target
Example #29
0
		corr_coef = numpy.corrcoef(numpy.array(fc),numpy.array(fc2))[0][1] # this is R
		line_x = numpy.linspace(numpy.array(fc).min(),numpy.array(fc).max()) # this is to have some points to actually draw the line. 

		plots=[]
		for i,classe in enumerate(all_classes):
			a=plt.plot(numpy.array(fc)[all_classes[classe]],numpy.array(fc2)[all_classes[classe]],'o',alpha=.5, color=colors[i], marker=markers[i], label=classe)
			plots.append(a)
		plots.append( plt.plot(line_x, line_x*lin_fit[0] + lin_fit[1] , '--b', label='$R^2$ = %.2f'%(corr_coef*corr_coef) )) #we append the plot of the line here
		kwarg={'size':6 }
		
		plt.legend(loc='upper right', prop=kwarg)
	
		if log2gene1:
			plt.xscale('log', basex=2)
			plt.xlabel('log2 expression of %s'%in_gene)
			plt.xlim(xmax=plt.xlim()[1]+2^10) #make room for the legend
		else:
			plt.xlabel('%s'%in_gene)
			plt.xlim(xmax=plt.xlim()[1]+1000) #make room for the legend
		
		if log2gene2:
			plt.yscale('log', basey=2)
			plt.ylabel('log2 expression of %s'%in_gene2)
			plt.xlim(xmax=plt.xlim()[1]+2^10) #make room for the legend
		else:
			
			plt.xlabel('%s'%in_gene)
			plt.xlim(xmax=plt.xlim()[1]+1000) #make room for the legend
		
		
		
            totalhist += hist
        f.close()
        print totalhist

        ax.plot(10 ** binmids, totalhist, color=colors[i], linewidth=1.5, alpha=0.8)
    ax.set_yscale("log")
    ax.set_xscale("log")

    ax.set_xlim(5.0e18, 1.0e24)
    ax.set_ylim(1, 1.0e5)

    set_ticks(ax, "0.6")
    ax.xaxis.grid(False, which="minor")
    ax.yaxis.grid(False, which="minor")

    plotlim = mpl.xlim() + mpl.ylim()
    print plotlim
    ax.imshow([0, 0], [1, 1], cmap=mp.cm.Grays, interpolation="bicubic", extent=plotlim)

    ax.set_xlabel(r"surface density / $\mathdefault{cm^{-2}}$", fontproperties=tfm, size=15)
    # ax.set_ylabel('d', fontproperties = tfm, size = 15)
    ax.set_ylabel(r"volume weighted PDF", fontproperties=tfm, size=15)

    (time, unit_t) = get_time(infoname)
    timeMyr = time * unit_t / 31557600.0 / 1.0e6
    horiz = 5.0e22
    vert = 2.0e4
    ax.text(
        horiz,
        vert,
        r"%.1f" % timeMyr,
Example #31
0
# In[15]:

X_set, Y_set = x_test, y_test
X1, X2 = np.meshgrid(
    np.arange(start=X_set[:, 0].min() - 1,
              stop=X_set[:, 0].max() + 1,
              step=0.01),
    np.arange(start=X_set[:, 1].min() - 1,
              stop=X_set[:, 1].max() + 1,
              step=0.01))
plt.contourf(X1,
             X2,
             classifier.predict(np.array([X1.ravel(),
                                          X2.ravel()]).T).reshape(X1.shape),
             alpha=0.75,
             cmap=ListedColormap(('cyan', 'yellow', 'blue')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(Y_set)):
    plt.scatter(X_set[Y_set == j, 0],
                X_set[Y_set == j, 1],
                c=ListedColormap(('red', 'green', 'yellow'))(i),
                label=j)
plt.title('Logistic Regression (Training set)')
plt.xlabel('PC1')
plt.ylabel('PC2')
plt.legend()
plt.show()

# In[ ]:
Example #32
0
		
		
		plots=[]
		for i,classe in enumerate(classes2use):
			a=plt.plot(numpy.array(fc)[classes2use[classe]],numpy.array(fc2)[classes2use[classe]],'o',alpha=.5, color=py_colors[i], marker=markers[i], label=classe)
			plots.append(a)
		if not log2gene1 and not log2gene2:
			plots.append( plt.plot(line_x, line_x*lin_fit[0] + lin_fit[1] , '--b', label='$R^2$ = %.2f'%(corr_coef*corr_coef) )) #we append the plot of the line here
		kwarg={'size':6 }
		
		plt.legend(loc='upper right', prop=kwarg)
	
		if log2gene1:
			plt.xscale('log', basex=2)
			plt.xlabel('Expression (log2) %s'%in_gene)
			plt.xlim(xmax=plt.xlim()[1]*1.1)
		else:
			plt.xlabel('%s'%in_gene)
			plt.xlim(xmax=plt.xlim()[1]*1.05) #make room for the legend
		
		if log2gene2:
			plt.yscale('log', basey=2)
			plt.ylabel('Expression (log2) %s'%in_gene2)
			plt.ylim(ymax=plt.ylim()[1]*1.1) #make room for the legend
		else:
			
			plt.ylabel('%s'%in_gene2)
			plt.ylim(ymax=plt.ylim()[1]*1.05) #make room for the legend
		
		
		
Example #33
0
                                    args=(ws, fs, model, tq_interpol))
    #if not load:
    #sampler.run_mcmc(pos, 15000, progress = True)
    #tau = sampler.get_autocorr_time()
    #print('autocorr',tau)
    #flattens the data according to burning/thinning from autocorrelation time
    #flat_samples = sampler.get_chain(discard=1000, thin=1, flat=True)
    #np.save('tq_{1}_samples_{0}.npy'.format(stack, bin_size),flat_samples)
    #else:
    #flat_samples = np.load('tq_{1}_samples_{0}.npy'.format(stack, bin_size))

    cv = lambda z: (1 / 2) * (1 + scipy.special.erf(z / np.sqrt(2)))

    plt.figure()
    plt.plot(tq_fine, pdf)
    plt.xlim(quantile(cv(-4)), quantile(cv(4)))
    plt.xlabel("$\\log_{10}(t_Q)$ (years)")
    plt.ylabel("Probability Density")

    tqmed = quantile(0.5)
    one_sig_upper = quantile(cv(1))
    one_sig_lower = quantile(cv(-1))

    two_sig_upper = quantile(cv(2))
    two_sig_lower = quantile(cv(-2))

    plt.axvline(x=one_sig_upper, color='red', linestyle='--')
    plt.axvline(x=one_sig_lower, color='red', linestyle='--')
    plt.axvline(x=two_sig_upper, color='blue', linestyle='--')
    plt.axvline(x=two_sig_lower, color='blue', linestyle='--')
    plt.axvline(x=tqmed, color='orange', linestyle='--')
### simulation
n_range = range(1, 5001)
lower_bounds = []
upper_bounds = []

for n in n_range:
    lower_bound, upper_bound = get_boundary(n)
    lower_bounds.append(lower_bound / n)
    upper_bounds.append(upper_bound / n)

plt.style.use('seaborn-notebook')
plt.plot(n_range, lower_bounds, label='lower_bounds\ndivided by n')
plt.plot(n_range, upper_bounds, label='upper_bounds\ndivided by n')
#plt.axvline(x=1000, color = 'red', linestyle = '--')
plt.legend(prop={'size': 13})
plt.xlim(1, 5000)
plt.xlabel("dimensions")
plt.title("Ratio between 2-standard devation boundaries and n as n increases",
          fontdict={'fontsize': 16})
plt.show()


#### how many points lie in the 10% period or outside
def get_pct_for_interval(n):
    sample = np.random.normal(size=(N, n))
    dist = np.square(np.linalg.norm(sample, axis=1))

    lower_interval = np.count_nonzero(dist < n * 0.95)
    middle_interval = np.count_nonzero((dist >= n * 0.95) & (dist <= n * 1.05))
    large_interval = np.count_nonzero(dist > n * 1.05)
Example #35
0
def LoadAndPlot(num_epochs, num_values, num_experiments):

    import numpy as np
    import matplotlib as plt
    import matplotlib
    matplotlib.use('Agg')
    #  matplotlib.use('Agg')plt.switch_backend('Agg')
    # plt.switch_backend('Agg')
    import matplotlib.pyplot as plt
    output_tr = np.fromfile('./output/output_tr',
                            sep="").reshape(num_experiments, num_values + 1, 2)
    output_sg = np.fromfile('./output/output_sg',
                            sep="").reshape(num_experiments, num_values + 1, 2)
    output_sga = np.fromfile('./output/output_sga',
                             sep="").reshape(num_experiments, num_values + 1,
                                             2)
    parameters_tr = np.fromfile('./output/parameters_tr', sep="")
    parameters_sg = np.fromfile('./output/parameters_sg', sep="")
    parameters_sga = np.fromfile('./output/parameters_sga', sep="")
    print 'This is the parameters or TRish'
    print parameters_tr
    print 'This is the parameters or SG'
    print parameters_sg
    print 'This is the parameters or SG Adaptive'
    print parameters_sga
    # print 'output'
    # print output_tr
    avg_output_tr = output_tr.mean(axis=0)
    avg_output_sg = output_sg.mean(axis=0)
    avg_output_sga = output_sga.mean(axis=0)

    sg_loss = np.trim_zeros(avg_output_sg[:, 0])
    sg_acc = np.trim_zeros(avg_output_sg[:, 1])
    x = np.arange(len(sg_acc)) / (1.0 * len(sg_acc)) * num_epochs
    # print 'average_output'
    # print avg_output_tr
    str_loss = np.trim_zeros(avg_output_tr[:, 0])
    str_acc = np.trim_zeros(avg_output_tr[:, 1])

    sga_loss = np.trim_zeros(avg_output_sga[:, 0])
    sga_acc = np.trim_zeros(avg_output_sga[:, 1])

    string_acc = "./figures/Mnist_testing_acc_{}epoch_avg.png".format(
        num_epochs)
    string_acc_multi = "./figures/Mnist_testing_acc_{}epoch_3alg.png".format(
        num_epochs)
    string_loss = "./figures/Mnist_training_loss_{}epoch_avg.png".format(
        num_epochs)
    string_loss_multi = "./figures/Mnist_training_loss_{}epoch_3alg.png".format(
        num_epochs)
    plt.figure(0)
    plt.plot(x[10:-1], str_acc[10:-1], 'b-', x[10:-1], sg_acc[10:-1], 'r-',
             sga_acc[10:-1], 'k-')
    plt.legend(['TRish', 'SG', 'SGA'], loc='lower right')
    plt.ylabel('Testing accuracy')
    plt.xlabel('Epochs')
    plt.xlim(0, float(num_epochs))
    plt.savefig(string_acc)
    plt.close()

    plt.figure(1)
    plt.plot(x[10:-1], str_loss[10:-1], 'b-', x[10:-1], sg_loss[10:-1], 'r-',
             sga_loss[10:-1], 'k-')
    #plt.plot(x,str_acc_mask ,'r-',x, sg_acc_mask,'b-')
    #plt.plot(x,str_acc ,'r-',x, sg_acc,'b-')
    #plt.legend(['SG', 'TRish'], loc='upper right')
    plt.legend(['TRish', 'SG', 'SGA'], loc='upper right')
    plt.ylabel('Training loss')
    plt.xlabel('Epochs')
    plt.xlim(0, float(num_epochs))
    plt.savefig(string_loss)
    plt.close()

    plt.figure(2)
    # plt.plot(x[10:-1], str_acc[10:-1],'b-',x[10:-1], sg_acc[10:-1],'r-')
    for i in range(num_experiments):
        plt.plot(x[10:100], output_tr[i, 10:-1, 0], 'b-')
        plt.plot(x[10:100], output_sg[i, 10:-1, 0], 'r-')
        plt.plot(x[10:100], output_sga[i, 10:-1, 0], 'k-')
    plt.legend(['TRish', 'SG', 'SGA'], loc='upper right')
    plt.ylabel('Training Loss')
    plt.xlabel('Epochs')
    plt.xlim(0, float(num_epochs))
    plt.savefig(string_loss_multi)
    plt.show()

    plt.figure(3)
    # plt.plot(x[10:-1], str_acc[10:-1],'b-',x[10:-1], sg_acc[10:-1],'r-')
    for i in range(num_experiments):
        plt.plot(x[10:100], output_tr[i, 10:-1, 1], 'b-')
        plt.plot(x[10:100], output_sg[i, 10:-1, 1], 'r-')
        plt.plot(x[10:100], output_sga[i, 10:-1, 1], 'k-')

    # plt.plot(x[10:100], output_tr[0,10:-1,0],'b-',x[10:100], output_tr[1,10:-1,0],'b-',
    # 	x[10:100], output_tr[2,10:-1,0],'b-')

    plt.legend(['TRish', 'SG', 'SGA'], loc='lower right')
    plt.ylabel('Testing accuracy')
    plt.xlabel('Epochs')
    plt.xlim(0, float(num_epochs))
    plt.savefig(string_acc_multi)
    plt.show()


# print avg_output_tr[avg_output_tr!=0]

# output_tune_tr = np.fromfile('./output/tune_trish',sep="").reshape(2,16,2)
# parameters_tune = np.fromfile('./output/tune_trish_param',sep="")
# output_tune_sg = np.fromfile('./output/tune_sg',sep="").reshape(2,16,2)
# parameters_tune_sg = np.fromfile('./output/tune_sg_param',sep="")
# print output_tune_tr

# print parameters_tune

# print output_tune_sg

# print parameters_tune_sg
Example #36
0
    Y = list(data_subset[to_plot])
    Y_err = [0] * len(Y)

#    Y_err = list(data_subset[to_plot + '_std'])
#    plt.errorbar(T[:], Y[:], yerr = Y_err, markersize = 5, marker = 'o', label = type)

    plt.plot(T[3:], Y[3:], markersize = 5, lw = 3, marker = 'o', label = type[4:-8] + ' spins')

    # if i == 0:
    #      plt.plot(T[:], Y[:], markersize = 5, lw = 3, marker = 'o', label = '1D')
    # elif i == 1 :
    #      plt.plot(T[1:], Y[1:], markersize = 5, lw = 3, marker = 'o', label = '1.5D')
    # elif i == 2 :
    #      plt.plot(T[1:], Y[1:], markersize = 5, lw = 3, marker = 'o', label = '2D')
    # else:
    #      plot(T[7:], Y[7:], markersize = 5, lw = 3, marker = 'o', label = '2.5D')

plt.xlabel('$T$', fontsize = 20)
plt.ylabel('$E$', fontsize = 20, rotation = 'horizontal', labelpad = 25)

#plt.axvline(x = 2.2, lw = 5, color = 'k', alpha = 0.2)

plt.subplots_adjust(left = 0.15, right = 0.92, top = 0.92, bottom = 0.15)
plt.tick_params(axis = 'both', which = 'major', labelsize = 20)


plt.xlim(left = 0, right = 5)
plt.ylim(bottom = -2.1, top = 0)
legend = plt.legend(fontsize = 18, loc = 2)
show()
         ''.format(roc_auc["macro"]),
         color='navy',
         linestyle=':',
         linewidth=4)

colors = cycle(['aqua', 'darkorange', 'cornflowerblue'])
for i, color in zip(range(2), colors):
    plt.plot(fpr[i],
             tpr[i],
             color=color,
             lw=2,
             label='ROC curve of class {0} (area = {1:0.2f})'
             ''.format(i, roc_auc[i]))

plt.plot([0, 1], [0, 1], 'k--', lw=2)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Some extension of Receiver operating characteristic to multi-class')
plt.legend(loc="lower right")
plt.show()

#%%
prediction2 = model.predict_classes(data3)
from sklearn.metrics import classification_report, confusion_matrix
print('Confusion Matrix')
print(confusion_matrix(labels2, prediction2))

print('Classification Report')
target_names = ['Benign', 'Malignant']
fontsize=18, color=colors[-1])


# fine tune
if cosmology == "FLCDM":
title = r"$H_{\rm{0}} \rm{[0, 150]} \ \ \ \Omega _{\rm{m}} \rm{[0.05, 0.5]}$"
elif cosmology == "FwCDM":
title = r"$H_{\rm{0}} \rm{[0, 150]} \ \ \ \Omega _{\rm{m}} \rm{[0.05, 0.5]} \ \ \  w \rm{[-2.5, 0.5]}$"
elif cosmology == "oLCDM":
title = r"$H_{\rm{0}} \rm{[0, 150]} \ \ \ \Omega _{\rm{m}} \rm{[0.05, 0.5]} \ \ \ \Omega _{\rm{k}} \rm{[-0.5, 0.5]}$"

plt.title(title, fontsize=18)
plt.xlabel(r"$H_{\rm{0}}\rm{\ [km\,s^{-1}\,Mpc^{-1}]}$", fontsize=24)
plt.ylabel("probability density", fontsize=18)
plt.yticks(fontsize=14)
plt.xticks(fontsize=20)
plt.yticks([])

legend = plt.legend()
legend.get_frame().set_alpha(0.0)
if cosmology in ["FLCDM", "oLCDM"]:
plt.xlim([48, 99])
plt.ylim([max(h)*0.005, max(h)*1.1])
elif cosmology == "FwCDM":
plt.xlim([48, 109])
plt.ylim([max(h)*0.005, max(h)*2.2])
plt.tight_layout()

plt.savefig(os.path.join(savedir, "H0.png"))
plt.show()
Example #39
0
File: plot.py Project: zhwlxl/pam
def plot_activities(person):
    '''
    Plot a high level activity plan for a single person
    '''

    #Load a df with a persons activty plan
    activities, start_times, end_times, durations = [], [], [], []

    for component in person.plan.day:
        activities.append(component.act.title())
        start_times.append(component.start_time.hour +
                           component.start_time.minute / 60)
        end_times.append(component.end_time.hour +
                         component.end_time.minute / 60)
        durations.append(component.duration.total_seconds() / 3600)

    df = pd.DataFrame(zip(activities, start_times, durations),
                      columns=['act', 'start_time', 'dur'])

    #Define a colour map for a unique list of activities

    colors = plt.cm.tab10.colors
    activities_unique = df['act'].unique()

    d_color = dict(zip(activities_unique, colors))

    df['color'] = df['act'].map(d_color)

    #Plotting
    fig, ax = plt.subplots(figsize=(16, 4))

    label_x, label_y = [], []

    for i in range(len(df)):
        y = 1
        data = df.iloc[i]
        ax.barh(y,
                width='dur',
                data=data,
                left='start_time',
                label='act',
                color='color')

        #Populate Labelling Params
        label_x.append(data['start_time'] + data['dur'] / 2)
        label_y.append(y)

    #Labels
    rects = ax.patches

    for x, y, rect, activity in zip(label_x, label_y, rects, activities):
        if rect.get_width() >= 3:
            ax.text(x,
                    y,
                    activity,
                    ha='center',
                    fontdict={
                        'color': 'white',
                        'size': 14,
                        'weight': 'bold'
                    })

    plt.xticks(range(25))
    plt.xlim(right=24)
    ax.get_yaxis().set_visible(False)
im = plt.imread('chicago.png')
implot = plt.imshow(im)

x = (df['west'] - df['west'].min())*477/(df['east'].max() - df['west'].min())
y = 798-(df['north'] - df['south'].min())*798/(df['north'].max() - df['south'].min())
s = df['currentspeed'] / df['currentspeed'].max()
plt.scatter(x,y,c=s,linewidth=0,s=1000,alpha=0.1)

#x0 = (df.ix[0]['west'] - df['west'].min())*477/(df['east'].max() - df['west'].min())
#y0 = 798-(df.ix[0]['north'] - df['south'].min())*798/(df['north'].max() - df['south'].min())
#plt.scatter(x0,y0,c='r',s=2000)
#x0 = (df.ix[0]['east'] - df['west'].min())*477/(df['east'].max() - df['west'].min())
#y0 = 798-(df.ix[0]['south'] - df['south'].min())*798/(df['north'].max() - df['south'].min())
#plt.scatter(x0,y0,c='r',s=2000)
plt.xlim(0,477)
plt.ylim(798,0)
plt.xticks([])
plt.yticks([])
#plt.plot([df['west'],df['west'],df['east'],df['east'],df['west']],[df['south'],df['north'],df['north'],df['south'],df['south']],linewidth=20,alpha=0.2)

# <codecell>

plt.figure(figsize=(15,15))

patches = []
verts = [(df['west'],df['south']),
    (df['west'],df['north']),
    (df['east'],df['north']),
    (df['east'],df['south']),
    (df['west'],df['south'])]