Exemplo n.º 1
0
def plot_horizontal_bar_from_cm(confusion_matrix = None, classes = []):
    # plt.rcdefaults()
    # plt.subplots(figsize = (10, 30))
    width = 0.30

    # Example data
    y_lables = 12 * ['a', 'b', 'c', 'd']
    y_pos = list(range(len(y_lables)))
    print(y_pos)
    true_positives = 12 * [8.84036186, 12.94095337, 11.19919226, 10.64395389]
    false_negatives = 12 * [1, 1, 1, 1]
    false_positives = 12 * [2, 13, 13, 3]

    TP = plt.barh(y_pos, true_positives, width, color = 'green', label = 'TP')
    FN = plt.barh(y_pos, false_negatives, width, label = 'FN', left = TP)
    plt.barh(y_pos, false_positives, width, label = 'FP', left = FN)
    # ax.barh([p + width for p in y_pos], false_negatives, width, label = 'FN')
    # ax.barh([p + width * 2 for p in y_pos], false_positives, width, label = 'FP')
    plt.set_yticks([p + 1.5 * width for p in y_pos])
    plt.set_yticklabels(y_lables)
    plt.invert_yaxis()  # labels read top-to-bottom
    plt.set_xlabel('Performance')
    plt.set_title('How fast do you want to go today?')

    plt.legend(['TP', 'FN', 'FP'], loc = 'upper right')
    plt.show()
Exemplo n.º 2
0
def label(plt, xlabel):
    rng = np.arange(122.7, 123.5, 0.1)
    plt.set_ylim(rng[0], rng[-1])
    plt.set_yticks(rng, ["%.1f" for i in rng])
    plt.set_xlabel(xlabel)
    plt.set_ylabel("Convertible Bond Price")
    plt.legend(["Binomial", "FDE - Implicit", "FDE - Crank-Nicolson", "FDE - Penalty"],
               prop={"size": "small"})
Exemplo n.º 3
0
def plot_barcode(vertices, edges = None, plt = plt, N_s = 50, k=4, r=.6, w=.5, annotate = False, triangulation='rips4'):
	vertices, tangents, curve, edges, simplices = hm.get_all(vertices, N_s, k, w, r, triangulation=triangulation, edges=edges)
	if edges is None: edges = _edges
	simplices = hm.get_ordered_simplices(vertices, curve, edges)
	barcode = bc.get_barcode(simplices, degree_values=curve[np.argsort(curve)])
	plot_barcode_gant(barcode, plt = plt, annotate = annotate)
	try: 
		plt.set_yticks([])
	except:
		plt.gca().set_yticks([])
def plot_confusion_matrix(cm, fig, counter, num_plots, title='Confusion matrix', cmap=plt.cm.Blues):
    ax = fig.add_subplot(1, num_plots, counter+1)
    ax.imshow(cm, interpolation='nearest', cmap=cmap)
    ax.set_title(title)
    tick_marks = np.arange(len(np.unique(test_labels_df['cat'])))
    plt.set_xticks(tick_marks, np.unique(test_labels_df['cat']), rotation=45)
    plt.set_yticks(tick_marks, np.unique(test_labels_df['cat']))
    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
Exemplo n.º 5
0
def plot_confusion_matrix(cm, fig, counter, num_plots, title='Confusion matrix', cmap=plt.cm.Blues):
    ax = fig.add_subplot(1, num_plots, counter+1)
    ax.imshow(cm, interpolation='nearest', cmap=cmap)
    ax.set_title(title)
    tick_marks = np.arange(len(np.unique(test_labels_df['cat'])))
    plt.set_xticks(tick_marks, np.unique(test_labels_df['cat']), rotation=45)
    plt.set_yticks(tick_marks, np.unique(test_labels_df['cat']))
    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
def plotstft(plt,
             samples,
             samplerate,
             binsize=2**10,
             plotpath=None,
             colormap="jet"):
    s = stft(samples, binsize)

    sshow, freq = logscale_spec(s, factor=1.0, sr=samplerate)

    ims = 20. * np.log10(np.abs(sshow) / 10e-6)  # amplitude to decibel

    timebins, freqbins = np.shape(ims)

    print("timebins: ", timebins)
    print("freqbins: ", freqbins)

    # plt.figure()
    plt.imshow(np.transpose(ims),
               origin="lower",
               aspect="auto",
               cmap=colormap,
               interpolation="none")
    # plt.figure.colorbar()

    plt.set_xlabel("time (s)")
    plt.set_ylabel("frequency (Hz)")
    plt.set_xlim([0, timebins - 1])
    plt.set_ylim([0, freqbins])

    xlocs = np.float32(np.linspace(0, timebins - 1, 5))
    plt.set_xticks(xlocs, [
        "%.02f" % l for l in ((xlocs * len(samples) / timebins) +
                              (0.5 * binsize)) / samplerate
    ])
    ylocs = np.int16(np.round(np.linspace(0, freqbins - 1, 10)))
    plt.set_yticks(ylocs, ["%.02f" % freq[i] for i in ylocs])

    # if plotpath:
    #     plt.savefig(plotpath, bbox_inches="tight")
    # else:
    #     plt.show()

    # plt.clf()

    return ims
Exemplo n.º 7
0
def getGraph(pos, neg):
    N = 1
    positive = pos
    negative = neg
    ind = np.arange(N)  # the x locations for the groups
    width = 0.02  # the width of the bars: can also be len(x) sequence

    fig, plt = plt.subplots()
    rects1 = plt.bar(ind, positive, width, color='#4bf3a2')

    rects2 = plt.bar(ind + width, negative, width, color='#f25454')

    # add some text for labels, title and axes ticks
    plt.set_xticklabels(ind)
    plt.set_yticks((np.arange(0, 1.1, 0.10)))
    plt.legend((rects1[0], rects2[0]), ('Postive', 'Negative'))

    canvas = fig.canvas
    return canvas
Exemplo n.º 8
0
 def __init__(self, figsize=(10, 10), dpi=100):
     Figure.__init__(self, figsize=figsize, dpi=dpi)
     titles = [{
         "title": "Orginalny obraz"
     }, {
         "title": "sinogram"
     }, {
         "title": "IRadon"
     }, {
         "title": "Sinogram po filtrze"
     }, {
         "title": "IRadon po filtrze"
     }]
     for i in range(1, 6):
         plt = self.add_subplot(2, 3, i)
         if "title" in titles[i - 1]:
             plt.set_title(titles[i - 1]["title"])
         plt.set_xticks([])
         plt.set_yticks([])
         self.plots[(2, 3, i)] = [plt, None]
Exemplo n.º 9
0
def plot_clustering(n_clusters, cluster_labels, X):
    plt.figure()
    sample_silhouette_values = silhouette_samples(X, cluster_labels)
    y_lower = 10
    for i in range(n_clusters):
        # Aggregate the silhouette scores for samples belonging to
        # cluster i, and sort them
        ith_cluster_silhouette_values = \
            sample_silhouette_values[cluster_labels == i]

        ith_cluster_silhouette_values.sort()

        size_cluster_i = ith_cluster_silhouette_values.shape[0]
        y_upper = y_lower + size_cluster_i

        color = plt.spectral(float(i) / n_clusters)
        plt.fill_betweenx(np.arange(y_lower, y_upper),
                          0, ith_cluster_silhouette_values,
                          facecolor=color, edgecolor=color, alpha=0.7)

        # Label the silhouette plots with their cluster numbers at the middle
        plt.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))

        # Compute the new y_lower for next plot
        y_lower = y_upper + 10  # 10 for the 0 samples

    plt.set_title("The silhouette plot for the various clusters.")
    plt.set_xlabel("The silhouette coefficient values")
    plt.set_ylabel("Cluster label")

    # The vertical line for average silhouette score of all the values
    plt.axvline(x=silhouette_avg, color="red", linestyle="--")

    plt.set_yticks([])  # Clear the yaxis labels / ticks
    plt.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
    plt.show()
Exemplo n.º 10
0
def plot_2D_scores(plt,fig,filename_data_pos,filename_data_neg,filename_data_grid,filename_scores_grid,th,noice_needed=0,caption='',filename_out=None):
    if not os.path.isfile(filename_data_pos): return
    if not os.path.isfile(filename_data_neg): return
    if not os.path.isfile(filename_data_grid): return

    data = tools_IO.load_mat(filename_scores_grid, dtype=numpy.chararray, delim='\t')
    data = data[1:,:]
    grid_scores = data[:, 1:].astype('float32')

    data = tools_IO.load_mat(filename_data_grid, dtype=numpy.chararray, delim='\t')
    data_grid = data[:,1:].astype('float32')

    data = tools_IO.load_mat(filename_data_pos, dtype=numpy.chararray, delim='\t')
    l1 = (data[:, 0]).astype('float32')
    x1 = data[:,1:].astype('float32')

    data = tools_IO.load_mat(filename_data_neg, dtype=numpy.chararray, delim='\t')
    l2 = (data[:, 0]).astype('float32')
    x2 = data[:,1:].astype('float32')

    X = numpy.vstack((x1,x2))
    labels = numpy.hstack((l1, l2)).astype(int)

    X1 = X[labels >  0]
    X0 = X[labels <= 0]

    #'''
    max = numpy.max(grid_scores)
    min = numpy.min(grid_scores)
    for i in range(0,grid_scores.shape[0]):
        if(grid_scores[i]>th):
            grid_scores[i]=(grid_scores[i]-th)/(max-th)
        else:
            grid_scores[i] = (grid_scores[i] - th) / (th-min)
    #'''

    S=int(math.sqrt(grid_scores.shape[0]))
    grid_scores=numpy.reshape(grid_scores,(S,S))

    minx=numpy.min(data_grid[:, 0])
    maxx=numpy.max(data_grid[:, 0])
    miny=numpy.min(data_grid[:, 1])
    maxy=numpy.max(data_grid[:, 1])


    if noice_needed>0:
        noice1 = 0.05-0.2*numpy.random.random_sample(X1.shape)
        noice0 = 0.05-0.2*numpy.random.random_sample(X0.shape)
        X1+=noice1
        X0+=noice0

    plt.set_title(caption)

    xx, yy = numpy.meshgrid(numpy.linspace(minx, maxx, num=S), numpy.linspace(miny, maxy,num=S))

    plt.contourf(xx, yy, numpy.flip(grid_scores,0), cmap=cm.coolwarm, alpha=.8)
    #plt.imshow(grid_scores, interpolation='bicubic',cmap=cm.coolwarm,extent=[minx,maxx,miny,maxy],aspect='auto')

    plt.plot(X0[:, 0], X0[:, 1], 'ro', color='blue', alpha=0.4)
    plt.plot(X1[: ,0], X1[:, 1], 'ro' ,color='red' , alpha=0.4)
    plt.grid()
    plt.set_xticks(())
    plt.set_yticks(())
    #fig.subplots_adjust(hspace=0.001,wspace =0.001)
    if filename_out is not None:
        plt.savefig(filename_out)

    return
Exemplo n.º 11
0
#
#plt.bar(np.arange(69),weights[0,:],label = features)
#

order = np.argsort(np.abs(weights[:]))[::-1]

plt.bar(np.arange(20),weights[order[:20]])
plt.xticks(np.arange(20),  features[order[:20]],fontsize =12)
plt.xticks(rotation="vertical")
plt.ylabel("Feature weights")
plt.savefig("/neurospin/brainomics/2016_schizConnect/analysis/all_studies+VIP/Freesurfer/all_subjects/results/ROIs_analysis/weights/svm_weights_top20.png")



plt.barh(np.arange(20),weights[order[:20]])
plt.set_yticks(np.arange(20))
plt.set_yticklabels(features[order[:20]])


plt.xticks(np.arange(20),  features[order[:20]],fontsize =12)
plt.xticks(rotation="vertical")
plt.ylabel("Feature weights")


plt.rc('font', family='serif')
plt.figure
plt.grid()
fig, ax = plt.subplots()
# Example data
features_names = features[order[:20]]
y_pos = np.arange(len(features_names))
Exemplo n.º 12
0
Arquivo: temp.py Projeto: shmakn99/GCN
import pickle 
import matplotlib.pyplot as plt
import numpy as np



# Example data
people = ('TP', 'FP', 'FN', 'TN')
y_pos = np.arange(len(people))
performance = (64354, 2701, 17007, 2417826)


plt.barh(y_pos, performance, align='center',
        color='green', ecolor='black')
plt.set_yticks(y_pos)
plt.set_yticklabels(people)
plt.invert_yaxis()  # labels read top-to-bottom
plt.set_xlabel('Performance')
plt.set_title('Precission - 0.959 Recal - 0.790')

plt.show()
Exemplo n.º 13
0
    J.append(calcJ(d, centers))

    return centers, J, closest


c, J, closest = kmeans(d, 2, 6)
print("centers")
print(c)
print("J=")
print(J)

plt.figure(1)
plt.subplot(511)
plt.title('plot-of-2D-data')
plt.set_yticks(scipy.arange(0, 5, 0.5))
plt.subplot(51 (n + 2))
plt.title('clustering of 2D data')
plt.set_yticks(scipy.arange(0, 5, 0.5))
plt.scatter(d[:, 0], d[:, 1], s=50, c=closest, alpha=0.5)
plt.scatter(c[:, 0], c[:, 1], s=80, c="green", alpha=0.5)
plt.subplots_adjust(hspace=0.8, wspace=0.5)
plt.savefig('ssdemo6.png')
plt.savefig('plot-of-2D-data-k-means.png')
plt.figure(2)
plt.scatter(d[:, 0], d[:, 1], s=80)
print("closest=")
print(closest)

plt.subplot(213)
plt.set_yticks(scipy.arange(4, 10, 0.5))
Exemplo n.º 14
0
#ax = fig.add_subplot(131)

#rects1 = ax.bar(x, stand_alone, width, label='Stand Alone')
#rects1 = ax.bar(x - width/2, stand_alone, width, color='cornflowerblue')
#rects1 = ax.bar(x,time, width)
rects1 = ax.bar(x, read, width, hatch='....', color='white', edgecolor='black')
#rects1 = ax.bar(x - width/2, stand_alone, width, label='Stand Alone')
#rects2 = ax.bar(x, collocated, width, label='Collocated')
#rects2 = ax.bar(x + width/2, collocated, width, color='orange')
#rects2 = ax.bar(x + width/2, collocated, width, label='Collocated')

# Add some text for labels, title and custom x-axis tick labels, etc.
plt.set_ylabel('Traffic in Million', fontsize=12)
plt.set_title('Read', fontsize=14)
plt.set_xticks(x)
plt.set_xticklabels(
    labels,
    fontsize=12,
)
#ax.set_xticklabels(labels, fontsize=12, rotation='vertical')
#ax.legend(loc=1, bbox_to_anchor=(0.5, 0., 0.5, 0.99))
plt.set_yticks(np.arange(0, max(read) + 2, 3))

x = np.arange(len(labels))  # the label locations

fig.subplots_adjust(wspace=.5)
plt.tight_layout()
plt.show()
fig.savefig('method-stream.png', dpi=100)
Exemplo n.º 15
0
import matplotlib.pyplot as plt

these_times = times[times.team == team]
plt.plot(these_times.time.as_matrix(),
         np.ones(len(these_times)), 'o')
plt.set_ylabel(team, rotation='horizontal',
               labelpad=30)
plt.set_ybound(0.5, 1.5)
plt.set_position([0.1, 0.1, 8.0, 1.0])
plt.set_yticks([])
Exemplo n.º 16
0
         alpha=alpha,
         height=bar_width,
         hatch=hatch1)
plt.barh(y=np.arange(len(x_data)) + bar_width,
         width=y_data2,
         label='RNR methods',
         color='indianred',
         alpha=alpha,
         height=bar_width,
         hatch=hatch2)

# 为Y轴设置刻度值
if y_label1:
    plt.yticks(np.arange(len(x_data)) + bar_width / 2, x_data, color='black')
else:
    plt.set_yticks([])
plt.xlabel(xlabel, fontdict=fontdict)
plt.xticks(color='black')
if add_baselines:
    plt.ylabel("Baselines", fontdict=fontdict)

plt.xlim(0.13, 0.18)
my_x_ticks = np.arange(0.13, 0.18, 0.01)
plt.xticks(my_x_ticks)
plt.legend(loc='lower center',
           bbox_to_anchor=(upper_dis, right_dis),
           ncol=ncol)

ax2 = fig.add_subplot(layout1, layout2, 2)
# ML100K: 2/4
# Delicious: 2/15
plt.show()

#Kernel Density Estimate (KDE). KDE is a fundamental data smoothing problem where inferences about 
#the population are made, based on a finite data sample. 
#It helps generate estimations of the overall distributions.

#estimations of the overall distributions
pd.plotting.scatter_matrix(retscomp, diagonal='kde', figsize=(10,10));

#heat maps to visualize the correlation ranges among the competing stocks. 
#The lighter the color, the more correlated the two stocks are
mk=plt.subplot()
plt.imshow(corr, cmap='hot', interpolation='none')
plt.colorbar()
plt.set_xticks(range(len(corr)), corr.columns)
plt.set_yticks(range(len(corr)), corr.columns)
plt.show()

#this might not show causality, and could just show the trend in the technology 
#industry rather than show how competing stocks

#Stock RETURNS n RISKS
#average of returns (Return Rate) and the standard deviation of returns (Risk).
plt.scatter(retscomp.mean(), retscomp.std())
plt.xlabel("Expected returns")
plt.ylabel("Risk")
plt.legend

for label, x, y in zip(retscomp.columns, retscomp.mean(), retscomp.std()):
    plt.annotate(
            label,
Exemplo n.º 18
0
def Pilot_Plot():
    # Creating big figure to hold all
    fig = plt.figure(figsize=(20, 16))

    # setting font size
    plt.rcParams.update({'font.size': 8})

    # # Turn off axis lines and ticks of the big subplot
    # ax.spines['top'].set_color('none')
    # ax.spines['bottom'].set_color('none')
    # ax.spines['left'].set_color('none')
    # ax.spines['right'].set_color('none')

    # Plotting estimated mu vs. response mu
    ax0 = fig.add_subplot(231)
    ax0.scatter(res_mu, est_mu, marker='.', label=f'n={len(res_mu)}')
    ax0.legend()
    ax0.set_title(
        'FOR VALIDATION: Participant response as a function of estimated mu')
    ax0.set_xlabel('response mu (radians)')
    ax0.set_ylabel('estimated mu (radians)')
    plt.set_xticks(card_direc)
    plt.set_yticks(card_direc)

    # Plotting MSE across presentation times
    ax1 = fig.add_subplot(232)
    ax1.set_title('MSE across stimulus presentation times')
    ax1.set_xlabel('Presentation Times (ms)')
    ax1.set_ylabel('MSE')
    # plt.bar(np.arange(8), durMSE, width=0.2)
    ax1.plot(np.arange(8), durMSE)
    ax1.set_xticks(np.arange(8), labels=durVal)

    #######################################################################################################
    # # Plotting response time vs. estimated mu, vs. response_mu
    # plt.figure(figsize=(13,6))
    #
    # plt.subplot(211)
    # plt.scatter(est_mu, data[colnames.index('keyRT')], marker='.', label=f'n={len(est_mu)}')
    # plt.legend()
    # plt.title('Response time as a function of estimated mean location')
    # plt.xlabel('est_mu (radians)')
    # plt.ylabel('response time (ms)')
    #
    # plt.subplot(212)
    # plt.scatter(res_mu, data[colnames.index('keyRT')], marker='.',label=f'n={len(res_mu)}')
    # plt.legend()
    # plt.title('Response time as a function of participant-observed mean location')
    # plt.xlabel('response mu (radians)')
    # plt.ylabel('response time (ms)')
    #
    # plt.tight_layout()
    # plt.show()

    # #######################################################################################################
    # ## Plotting cardinal vs. oblique MSE
    # plt.figure(figsize=(4,3))
    # plt.title('MSE, by orientation of MSE \n(each direction padded by pi/8 radians')
    # plt.bar([0, 1], [card_MSE, obli_MSE])
    # plt.ylabel('MSE')
    # plt.xticks([0,1], ('cardinal','oblique'))
    # plt.show()

    #######################################################################################################
    ## Plotting relationship of accuracy with RT and PT
    ## TODO: Plot SAT curve after fitting logistic function
    plt.figure(figsize=(14, 4))
    plt.rcParams.update({'font.size': 6})

    ax2 = fig.add_subplot(233)
    # plt.title('Response time-Accuracy')
    # plt.xlabel('Response time (ms)')
    # plt.ylabel('Accuracy (percent distance of response mu from est_mu)')
    # plt.scatter(keyRT, ERxTrials * 100, marker='.', s=1)
    # plt.xticks(durVal, labels=durVal)

    ax2.set_title('Presentation Time vs. Accuracy')
    ax2.set_xlabel('Presentation time (ms)')
    ax2.set_ylabel('Accuracy (percent distance of response mu from est_mu)')
    ax2.scatter(vizDur, res_acc * 100)
    ax2.set_xticks(durVal, labels=durVal)

    # Boxplot, Response time median, mean, IQR for each stimulus duration
    ax3 = fig.add_subplot(234)
    ax3.set_title(
        'Response time, by stimulus duration \n(orange = median, green = mean)'
    )
    ax3.set_ylabel('Response time (ms)')
    ax3.set_xlabel('Presentation duration (ms)')
    ax3.boxplot(dur_RT, meanline=True, showmeans=True)
    ax3.set_xticks(np.arange(1, len(durVal) + 1), labels=durVal)

    #######################################################################################################
    # ## Accuracy as a function of distance of initial probe to (1) response mu and (2) estimated mu
    # fig = plt.figure(figsize=(10,5))
    #
    # ax = fig.add_subplot(111)  # The big subplot
    # ax1 = fig.add_subplot(211)
    # ax2 = fig.add_subplot(212)
    #
    # # Turn off axis lines and ticks of the big subplot
    # ax.spines['top'].set_color('none')
    # ax.spines['bottom'].set_color('none')
    # ax.spines['left'].set_color('none')
    # ax.spines['right'].set_color('none')
    # ax.tick_params(labelcolor='w', top='off', bottom='off', left='off', right='off')
    # ax.set_ylabel('Trial Accuracy')
    #
    # # fig.suptitle('Accuracy vs. probe locations')
    # ax1.scatter(probe2est, ERxTrials, marker='.', s=1)
    # ax1.set_xlabel('distance from initial probe to estimated mu (radians)')
    # ax2.scatter(probe2res, ERxTrials, marker='.', s=1)
    # ax2.set_xlabel('distance from initial probe to response mu (radians)')
    # plt.tight_layout()
    #
    # plt.figure(figsize=(14, 4))
    # plt.rcParams.update({'font.size': 6})

    ax4 = fig.add_subplot(235)
    plt.title('Presentation Time-Accuracy Curve')
    plt.xlabel('Presentation time (ms)')
    plt.ylabel('Accuracy (percent distance of response mu from est_mu)')
    plt.scatter(vizDur, res_acc * 100)
    plt.xticks(durVal, labels=durVal)

    plt.title('Error vs. Propmix')
    plt.xlabel('Response time (ms)')
    plt.ylabel('Accuracy (percent distance of response mu from est_mu)')
    plt.scatter(keyRT, res_acc * 100, marker='.', s=1)
    # plt.xticks(durVal, labels=durVal)

    plt.figure(figsize=(12, 4))
    plt.rcParams.update({'font.size': 12})
    plt.suptitle('Parameter dependency on response time')
    plt.rcParams.update({'font.size': 8})
    plt.subplot(121)
    plt.title(
        'Mean response time as a function of kappa (concentration) of stimulus'
    )
    for i, x in enumerate(propVal):
        plt.plot(kpVal[i], kp_RT_mean[i], label=f'propmix = {x}')
    plt.legend()
    plt.xlabel('estimated kappa')
    plt.ylabel('mean RT (ms)')
    plt.title('RT by kappa')

    ## All kappa
    # plt.plot(kapVal, kap_RT_mean)
    # plt.xlabel('kappa')
    # plt.ylabel('mean RT (ms)')

    plt.subplot(122)
    plt.bar(propVal, prop_RT_mean)
    plt.title('Mean response time as a function of noise present')
    plt.xlabel(
        'Proportion of uniform noise to von Mises distribution in stimulus')
    plt.ylabel('mean RT (ms)')
    plt.xticks(propVal)