Python pylab.yticks() Examples

The following are 25 code examples of pylab.yticks(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pylab , or try the search function .
Example #1
Source File: View.py    From Deep-Spying with Apache License 2.0 9 votes vote down vote up
def plot_confusion_matrix(self, matrix, labels):
        if not self.to_save and not self.to_show:
            return

        pylab.figure()
        pylab.imshow(matrix, interpolation='nearest', cmap=pylab.cm.jet)
        pylab.title("Confusion Matrix")

        for i, vi in enumerate(matrix):
            for j, vj in enumerate(vi):
                pylab.annotate("%.1f" % vj, xy=(j, i), horizontalalignment='center', verticalalignment='center', fontsize=9)

        pylab.colorbar()

        classes = np.arange(len(labels))
        pylab.xticks(classes, labels)
        pylab.yticks(classes, labels)

        pylab.ylabel('Expected label')
        pylab.xlabel('Predicted label') 
Example #2
Source File: compare_overbeek_profiles.py    From SelfTarget with MIT License 6 votes vote down vote up
def plotInFrame(overbeek_inframes, ours_inframes, oof_sel_overbeek_ids, pred_results_dir):

    PL.figure(figsize=(4.2,4.2))
    data = pd.read_csv(pred_results_dir + '/old_new_kl_predicted_summaries.txt', sep='\t').fillna(-1.0)
    label1, label2 = 'New 2x800x In Frame Perc', 'New 1600x In Frame Perc'
    xdata, ydata = data[label1], data[label2]
    PL.plot(xdata,ydata, '.', label='Synthetic between library (R=%.2f)' %  pearsonr(xdata,ydata)[0], color='C0',alpha=0.15)
    PL.plot(overbeek_inframes, ours_inframes, '^', label='Synthetic vs Endogenous (R=%.2f)' % pearsonr(overbeek_inframes, ours_inframes)[0], color='C1')
    for (x,y,id) in zip(overbeek_inframes, ours_inframes, oof_sel_overbeek_ids):
        if abs(x-y) > 25.0: PL.text(x,y,id)
    PL.plot([0,100],[0,100],'k--')
    PL.ylabel('Percent In-Frame Mutations')
    PL.xlabel('Percent In-Frame Mutations')
    PL.legend()
    PL.xticks([],[])
    PL.yticks([],[])
    PL.show(block=False)
    saveFig('in_frame_full_scatter') 
Example #3
Source File: vim-profiler.py    From vim-profiler with GNU General Public License v3.0 6 votes vote down vote up
def plot(self):
        """
        Plot startup data.
        """
        import pylab

        print("Plotting result...", end="")
        avg_data = self.average_data()
        avg_data = self.__sort_data(avg_data, False)
        if len(self.raw_data) > 1:
            err = self.stdev_data()
            sorted_err = [err[k] for k in list(zip(*avg_data))[0]]
        else:
            sorted_err = None
        pylab.barh(range(len(avg_data)), list(zip(*avg_data))[1],
                   xerr=sorted_err, align='center', alpha=0.4)
        pylab.yticks(range(len(avg_data)), list(zip(*avg_data))[0])
        pylab.xlabel("Average startup time (ms)")
        pylab.ylabel("Plugins")
        pylab.show()
        print(" done.") 
Example #4
Source File: vim-plugins-profile.py    From vim-plugins-profile with GNU General Public License v3.0 6 votes vote down vote up
def plot(self):
        """
        Plot startup data.
        """
        import pylab

        print("Plotting result...", end="")
        avg_data = self.average_data()
        avg_data = self.__sort_data(avg_data, False)
        if len(self.raw_data) > 1:
            err = self.stdev_data()
            sorted_err = [err[k] for k in list(zip(*avg_data))[0]]
        else:
            sorted_err = None
        pylab.barh(range(len(avg_data)), list(zip(*avg_data))[1],
                   xerr=sorted_err, align='center', alpha=0.4)
        pylab.yticks(range(len(avg_data)), list(zip(*avg_data))[0])
        pylab.xlabel("Average startup time (ms)")
        pylab.ylabel("Plugins")
        pylab.show()
        print(" done.") 
Example #5
Source File: plotting.py    From smallrnaseq with GNU General Public License v3.0 6 votes vote down vote up
def heatmap(df,fname=None,cmap='seismic',log=False):
    """Plot a heat map"""

    from matplotlib.colors import LogNorm
    f=plt.figure(figsize=(8,8))
    ax=f.add_subplot(111)
    norm=None
    df=df.replace(0,.1)
    if log==True:
        norm=LogNorm(vmin=df.min().min(), vmax=df.max().max())
    hm = ax.pcolor(df,cmap=cmap,norm=norm)
    plt.colorbar(hm,ax=ax,shrink=0.6,norm=norm)
    plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
    plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns, rotation=90)
    #ax.axvline(4, color='gray'); ax.axvline(8, color='gray')
    plt.tight_layout()
    if fname != None:
        f.savefig(fname+'.png')
    return ax 
Example #6
Source File: functional_map.py    From cmm with GNU General Public License v2.0 6 votes vote down vote up
def plot_functional_map(C, newfig=True):
    vmax = max(np.abs(C.max()), np.abs(C.min()))
    vmin = -vmax
    C = ((C - vmin) / (vmax - vmin)) * 2 - 1
    if newfig:
        pl.figure(figsize=(5,5))
    else:
        pl.clf()
    ax = pl.gca()
    pl.pcolor(C[::-1], edgecolor=(0.9, 0.9, 0.9, 1), lw=0.5,
              vmin=-1, vmax=1, cmap=nice_mpl_color_map())
    # colorbar
    tick_locs   = [-1., 0.0, 1.0]
    tick_labels = ['min', 0, 'max']
    bar = pl.colorbar()
    bar.locator = matplotlib.ticker.FixedLocator(tick_locs)
    bar.formatter = matplotlib.ticker.FixedFormatter(tick_labels)
    bar.update_ticks()
    ax.set_aspect(1)
    pl.xticks([])
    pl.yticks([])
    if newfig:
        pl.show() 
Example #7
Source File: transfer_learning.py    From plastering with MIT License 6 votes vote down vote up
def plot_confusion_matrix(test_label, pred):

    mapping = {1:'co2',2:'humidity',3:'pressure',4:'rmt',5:'status',6:'stpt',7:'flow',8:'HW sup',9:'HW ret',10:'CW sup',11:'CW ret',12:'SAT',13:'RAT',17:'MAT',18:'C enter',19:'C leave',21:'occu',30:'pos',31:'power',32:'ctrl',33:'fan spd',34:'timer'}
    cm_ = CM(test_label, pred)
    cm = normalize(cm_.astype(np.float), axis=1, norm='l1')
    fig = pl.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(cm, cmap=Color.YlOrBr)
    fig.colorbar(cax)
    for x in range(len(cm)):
        for y in range(len(cm)):
            ax.annotate(str("%.3f(%d)"%(cm[x][y], cm_[x][y])), xy=(y,x),
                        horizontalalignment='center',
                        verticalalignment='center',
                        fontsize=9)
    cm_cls =np.unique(np.hstack((test_label, pred)))
    cls = []
    for c in cm_cls:
        cls.append(mapping[c])
    pl.yticks(range(len(cls)), cls)
    pl.ylabel('True label')
    pl.xticks(range(len(cls)), cls)
    pl.xlabel('Predicted label')
    pl.title('Confusion Matrix (%.3f)'%(ACC(pred, test_label)))
    pl.show() 
Example #8
Source File: dependencygraph.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def malt_demo(nx=False):
    """
    A demonstration of the result of reading a dependency
    version of the first sentence of the Penn Treebank.
    """
    dg = DependencyGraph("""Pierre  NNP     2       NMOD
Vinken  NNP     8       SUB
,       ,       2       P
61      CD      5       NMOD
years   NNS     6       AMOD
old     JJ      2       NMOD
,       ,       2       P
will    MD      0       ROOT
join    VB      8       VC
the     DT      11      NMOD
board   NN      9       OBJ
as      IN      9       VMOD
a       DT      15      NMOD
nonexecutive    JJ      15      NMOD
director        NN      12      PMOD
Nov.    NNP     9       VMOD
29      CD      16      NMOD
.       .       9       VMOD
""")
    tree = dg.tree()
    print tree.pprint()
    if nx:
        #currently doesn't work
        import networkx as NX
        import pylab as P

        g = dg.nx_graph()
        g.info()
        pos = NX.spring_layout(g, dim=1)
        NX.draw_networkx_nodes(g, pos, node_size=50)
        #NX.draw_networkx_edges(g, pos, edge_color='k', width=8)
        NX.draw_networkx_labels(g, pos, dg.nx_labels)
        P.xticks([])
        P.yticks([])
        P.savefig('tree.png')
        P.show() 
Example #9
Source File: eigenfaces.py    From machine-learning with GNU General Public License v3.0 5 votes vote down vote up
def plot_gallery(images, titles, h, w, n_row=3, n_col=4):
    """Helper function to plot a gallery of portraits"""
    pl.figure(figsize=(1.8 * n_col, 2.4 * n_row))
    pl.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)
    for i in range(n_row * n_col):
        pl.subplot(n_row, n_col, i + 1)
        pl.imshow(images[i].reshape((h, w)), cmap=pl.cm.gray)
        pl.title(titles[i], size=12)
        pl.xticks(())
        pl.yticks(())


# plot the result of the prediction on a portion of the test set 
Example #10
Source File: iris_recognition.py    From GmdhPy with MIT License 5 votes vote down vote up
def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues):
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(iris.target_names))
    plt.xticks(tick_marks, iris.target_names, rotation=45)
    plt.yticks(tick_marks, iris.target_names)
    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label') 
Example #11
Source File: plot_kl_analysis.py    From SelfTarget with MIT License 5 votes vote down vote up
def plotHeatMap(data, col='KL without null', label=''):

    #Compute and collate medians
    sel_cols = [x for x in data.columns if col in x]
    cmp_meds = data[sel_cols].median(axis=0)
    samples = sortSampleNames(getUniqueSamples(sel_cols))
    cell_lines = ['CHO', 'E14TG2A', 'BOB','RPE1', 'HAP1','K562','eCAS9','TREX2']
    sample_idxs = [(cell_lines.index(parseSampleName(x)[0]),x) for x in getUniqueSamples(sel_cols)]
    sample_idxs.sort()
    samples = [x[1] for x in sample_idxs]

    N = len(samples)
    meds = np.zeros((N,N))
    for colname in sel_cols:
        dir1, dir2 = getDirsFromFilename(colname.split('$')[-1])
        idx1, idx2 = samples.index(dir1), samples.index(dir2)
        meds[idx1,idx2] = cmp_meds[colname]
        meds[idx2,idx1] = cmp_meds[colname]

    for i in range(N):
        print(' '.join(['%.2f' % x for x in meds[i,:]]))
    print( np.median(meds[:,:-4],axis=0))

	#Display in Heatmap
    PL.figure(figsize=(5,5))
    PL.imshow(meds, cmap='hot_r', vmin = 0.0, vmax = 3.0, interpolation='nearest')
    PL.colorbar()
    PL.xticks(range(N))
    PL.yticks(range(N))
    PL.title("Median KL") # between %d mutational profiles (for %s with >%d mutated reads)" % (col, len(data), label, MIN_READS))
    ax1 = PL.gca()
    ax1.set_yticklabels([getSimpleName(x) for x in samples], rotation='horizontal')
    ax1.set_xticklabels([getSimpleName(x) for x in samples], rotation='vertical')
    PL.subplots_adjust(left=0.25,right=0.95,top=0.95, bottom=0.25)
    PL.show(block=False) 
    saveFig('median_kl_heatmap_cell_lines') 
Example #12
Source File: review_analysis.py    From yelp with GNU Lesser General Public License v2.1 5 votes vote down vote up
def simple_lineal_regression(file_path):
        records = ReviewETL.load_file(file_path)
        data = [[record['review_count']] for record in records]
        ratings = [record['stars'] for record in records]

        num_testing_records = int(len(ratings) * 0.8)
        training_data = data[:num_testing_records]
        testing_data = data[num_testing_records:]
        training_ratings = ratings[:num_testing_records]
        testing_ratings = ratings[num_testing_records:]

        # Create linear regression object
        regr = linear_model.LinearRegression()

        # Train the model using the training sets
        regr.fit(training_data, training_ratings)

        # The coefficients
        print('Coefficients: \n', regr.coef_)
        print('Intercept: \n', regr.intercept_)
        # The root mean square error
        print("RMSE: %.2f"
              % (np.mean(
            (regr.predict(testing_data) - testing_ratings) ** 2)) ** 0.5)

        print(
            'Variance score: %.2f' % regr.score(testing_data, testing_ratings))

        # Plot outputs
        import pylab as pl

        pl.scatter(testing_data, testing_ratings, color='black')
        pl.plot(testing_data, regr.predict(testing_data), color='blue',
                linewidth=3)

        pl.xticks(())
        pl.yticks(())

        pl.show() 
Example #13
Source File: build_diagram.py    From NEUCOGAR with GNU General Public License v2.0 5 votes vote down vote up
def spikes_diagram(ts, gids, name, path):
    """
    Function for making spike diagrams
    :param ts:   (list) times
    :param gids: (list) global IDs of neurons
    :param name: (str) name of brain part
    :param path: (str) path to save results
    :return: None
    """
    pylab.figure()
    color_marker = "."
    color_bar = "blue"
    color_edge = "black"
    ylabel = "Neuron ID"
    hist_binwidth = 5.0
    location = pylab.axes([0.1, 0.3, 0.85, 0.6])
    pylab.plot(ts, gids, color_marker)
    pylab.ylabel(ylabel)
    xlim = pylab.xlim()
    pylab.xticks([])
    pylab.axes([0.1, 0.1, 0.85, 0.17])
    t_bins = numpy.arange(numpy.amin(ts), numpy.amax(ts), hist_binwidth)
    n, bins = pylab.histogram(ts, bins=t_bins)
    num_neurons = len(numpy.unique(gids))
    heights = (1000 * n / (hist_binwidth * num_neurons))
    # FixMe t_bins[:-1] should work without cutting the end value
    pylab.bar(t_bins[:-1], heights, width=hist_binwidth, color=color_bar, edgecolor=color_edge)
    pylab.yticks([int(a) for a in numpy.linspace(0.0, int(max(heights) * 1.1) + 5, 4)])
    pylab.ylabel("Rate (Hz)")
    pylab.xlabel("Time (ms)")
    pylab.grid(True)
    pylab.axes(location)
    pylab.title(name)
    pylab.xlim(xlim)
    pylab.draw()
    pylab.savefig("{0}{1}.png".format(path, name), dpi=dpi_n, format='png')
    pylab.close() 
Example #14
Source File: c10_20_6_figures.py    From Python-for-Finance-Second-Edition with MIT License 5 votes vote down vote up
def graph(text,text2=''): 
    pl.xticks(())
    pl.yticks(())
    pl.xlim(0,30)
    pl.ylim(0,20) 
    pl.plot([x,x],[0,3])
    pl.text(x,-2,"X");
    pl.text(0,x,"X")
    pl.text(x,x*1.7, text, ha='center', va='center',size=10, alpha=.5) 
    pl.text(-5,10,text2,size=25) 
Example #15
Source File: dispersion.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def dispersion_plot(text, words, ignore_case=False):
    """
    Generate a lexical dispersion plot.

    :param text: The source text
    :type text: list(str) or enum(str)
    :param words: The target words
    :type words: list of str
    :param ignore_case: flag to set if case should be ignored when searching text
    :type ignore_case: bool
    """

    try:
        import pylab
    except ImportError:
        raise ValueError('The plot function requires the matplotlib package (aka pylab).'
                     'See http://matplotlib.sourceforge.net/')

    text = list(text)
    words.reverse()

    if ignore_case:
        words_to_comp = map(str.lower, words)
        text_to_comp = map(str.lower, text)
    else:
        words_to_comp = words
        text_to_comp = text

    points = [(x,y) for x in range(len(text_to_comp))
                    for y in range(len(words_to_comp))
                    if text_to_comp[x] == words_to_comp[y]]
    if points:
        x, y = zip(*points)
    else:
        x = y = ()
    pylab.plot(x, y, "b|", scalex=.1)
    pylab.yticks(range(len(words)), words, color="b")
    pylab.ylim(-1, len(words))
    pylab.title("Lexical Dispersion Plot")
    pylab.xlabel("Word Offset")
    pylab.show() 
Example #16
Source File: active_learning.py    From plastering with MIT License 5 votes vote down vote up
def plot_confusion_matrix(self, label_test, fn_test):

        fn_preds = self.clf.predict(fn_test)
        acc = accuracy_score(label_test, fn_preds)

        cm_ = CM(label_test, fn_preds)
        cm = normalize(cm_.astype(np.float), axis=1, norm='l1')

        fig = pl.figure()
        ax = fig.add_subplot(111)
        cax = ax.matshow(cm)
        fig.colorbar(cax)
        for x in range(len(cm)):
            for y in range(len(cm)):
                ax.annotate(str("%.3f(%d)"%(cm[x][y], cm_[x][y])), xy=(y,x),
                            horizontalalignment='center',
                            verticalalignment='center',
                            fontsize=10)
        cm_cls =np.unique(np.hstack((label_test,fn_preds)))

        cls = []
        for c in cm_cls:
            cls.append(mapping[c])
        pl.yticks(range(len(cls)), cls)
        pl.ylabel('True label')
        pl.xticks(range(len(cls)), cls)
        pl.xlabel('Predicted label')
        pl.title('Mn Confusion matrix (%.3f)'%acc)

        pl.show() 
Example #17
Source File: spectrogram.py    From spectrum with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot(self, filename=None, vmin=None, vmax=None, cmap='jet_r'):
        import pylab
        pylab.clf()
        pylab.imshow(-np.log10(self.results[self._start_y:,:]), 
            origin="lower",
            aspect="auto", cmap=cmap, vmin=vmin, vmax=vmax)
        pylab.colorbar()

        # Fix xticks
        XMAX = float(self.results.shape[1])  # The max integer on xaxis
        xpos = list(range(0, int(XMAX), int(XMAX/5)))
        xx = [int(this*100)/100 for this in np.array(xpos) / XMAX * self.duration]
        pylab.xticks(xpos, xx, fontsize=16)

        # Fix yticks
        YMAX = float(self.results.shape[0])  # The max integer on xaxis
        ypos = list(range(0, int(YMAX), int(YMAX/5)))
        yy = [int(this) for this in np.array(ypos) / YMAX * self.sampling]
        pylab.yticks(ypos, yy, fontsize=16)

        #pylab.yticks([1000,2000,3000,4000], [5500,11000,16500,22000], fontsize=16)
        #pylab.title("%s echoes" %  filename.replace(".png", ""), fontsize=25)
        pylab.xlabel("Time (seconds)", fontsize=25)
        pylab.ylabel("Frequence (Hz)", fontsize=25)
        pylab.tight_layout()
        if filename:
            pylab.savefig(filename) 
Example #18
Source File: __init__.py    From EDeN with MIT License 4 votes vote down vote up
def plot_embedding(data_matrix, y,
                   labels=None,
                   image_file_name=None,
                   title=None,
                   cmap='rainbow',
                   density=False):
    """plot_embedding."""
    import matplotlib.pyplot as plt
    from matplotlib import offsetbox
    from PIL import Image
    from eden.embedding import embed_dat_matrix_two_dimensions

    if title is not None:
        plt.title(title)
    if density:
        embed_dat_matrix_two_dimensions(data_matrix,
                                        y=y,
                                        instance_colormap=cmap)
    else:
        plt.scatter(data_matrix[:, 0], data_matrix[:, 1],
                    c=y,
                    cmap=cmap,
                    alpha=.7,
                    s=30,
                    edgecolors='black')
        plt.xticks([])
        plt.yticks([])
        plt.axis('off')
    if image_file_name is not None:
        num_instances = data_matrix.shape[0]
        ax = plt.subplot(111)
        for i in range(num_instances):
            img = Image.open(image_file_name + str(i) + '.png')
            imagebox = offsetbox.AnnotationBbox(
                offsetbox.OffsetImage(img, zoom=1),
                data_matrix[i],
                pad=0,
                frameon=False)
            ax.add_artist(imagebox)
    if labels is not None:
        for id in range(data_matrix.shape[0]):
            label = str(labels[id])
            x = data_matrix[id, 0]
            y = data_matrix[id, 1]
            plt.annotate(label,
                         xy=(x, y),
                         xytext=(0, 0),
                         textcoords='offset points') 
Example #19
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 4 votes vote down vote up
def make_inset(figure="current", width=1, height=1):
    """

    This guy makes the figure thick and small, like an inset.
    Currently assumes there is only one set of axes in the window!

    """

    # get the current figure if we're not supplied with one
    if figure == "current": figure = _pylab.gcf()

    # get the window
    w = figure.canvas.GetParent()

    # first set the size of the window
    w.SetSize([220,300])

    # we want thick axis lines
    figure.axes[0].get_frame().set_linewidth(3.0)

    # get the tick lines in one big list
    xticklines = figure.axes[0].get_xticklines()
    yticklines = figure.axes[0].get_yticklines()

    # set their marker edge width
    _pylab.setp(xticklines+yticklines, mew=2.0)

    # set what kind of tickline they are (outside axes)
    for l in xticklines: l.set_marker(_mpl.lines.TICKDOWN)
    for l in yticklines: l.set_marker(_mpl.lines.TICKLEFT)

    # get rid of the top and right ticks
    figure.axes[0].xaxis.tick_bottom()
    figure.axes[0].yaxis.tick_left()

    # we want bold fonts
    _pylab.xticks(fontsize=20, fontweight='bold', fontname='Arial')
    _pylab.yticks(fontsize=20, fontweight='bold', fontname='Arial')

    # we want to give the labels some breathing room (1% of the data range)
    figure.axes[0].xaxis.set_ticklabels([])
    figure.axes[0].yaxis.set_ticklabels([])


    # set the position/size of the axis in the window
    figure.axes[0].set_position([0.1,0.1,0.1+0.7*width,0.1+0.7*height])

    # set the axis labels to empty (so we can add them with a drawing program)
    figure.axes[0].set_title('')
    figure.axes[0].set_xlabel('')
    figure.axes[0].set_ylabel('')

    # set the position of the legend far away
    figure.axes[0].legend=None

    # zoom!
    auto_zoom(figure.axes[0], 0.07, 0.07) 
Example #20
Source File: galaxy10.py    From astroNN with MIT License 4 votes vote down vote up
def galaxy10_confusion(confusion_mat):
    """
    NAME:
        galaxy10_confusion
    PURPOSE:
        to plot confusion matrix
    INPUT:
        confusion_mat (ndarray): An integer 0-9
    OUTPUT:
        (string): Name of the class
    HISTORY:
        2018-Feb-11 - Written - Henry Leung (University of Toronto)
    """
    import pylab as plt

    conf_arr = confusion_mat.astype(int)

    norm_conf = []
    a = np.max(conf_arr)
    for i in conf_arr:
        tmp_arr = []
        for j in i:
            tmp_arr.append(float(j) / float(a))
        norm_conf.append(tmp_arr)

    fig, ax = plt.subplots(1, figsize=(10, 10.5), dpi=100)
    fig.suptitle("Confusion Matrix for Galaxy10 trained by astroNN", fontsize=18)
    ax.set_aspect(1)
    ax.imshow(np.array(norm_conf), cmap=plt.get_cmap('Blues'), interpolation='nearest')

    width, height = conf_arr.shape

    for x in range(width):
        for y in range(height):
            ax.annotate(str(conf_arr[x][y]), xy=(y, x),
                        horizontalalignment='center',
                        verticalalignment='center')

    alphabet = '0123456789'
    plt.xticks(range(width), alphabet[:width], fontsize=20)
    plt.yticks(range(height), alphabet[:height], fontsize=20)
    ax.set_ylabel('Prediction class by astroNN', fontsize=18)
    ax.set_xlabel('True class', fontsize=18)
    fig.tight_layout(rect=[0, 0.00, 0.8, 0.96])
    fig.show()

    return None 
Example #21
Source File: helper.py    From KittiSeg with MIT License 4 votes vote down vote up
def plotPrecisionRecall(precision, recall, outFileName, Fig=None, drawCol=1, textLabel = None, title = None, fontsize1 = 24, fontsize2 = 20, linewidth = 3):
    '''
    
    :param precision:
    :param recall:
    :param outFileName:
    :param Fig:
    :param drawCol:
    :param textLabel:
    :param fontsize1:
    :param fontsize2:
    :param linewidth:
    '''
                      
    clearFig = False  
           
    if Fig == None:
        Fig = pylab.figure()
        clearFig = True
        
    #tableString = 'Algo avgprec Fmax prec recall accuracy fpr Q(TonITS)\n'
    linecol = ['g','m','b','c']
    #if we are evaluating SP, then BL is available
    #sectionName = 'Evaluation_'+tag+'PxProb'
    #fullEvalFile = os.path.join(eval_dir,evalName)
    #Precision,Recall,evalString = readEvaluation(fullEvalFile,sectionName,AlgoLabel)

    pylab.plot(100*recall, 100*precision, linewidth=linewidth, color=linecol[drawCol], label=textLabel)


    #writing out PrecRecall curves as graphic
    setFigLinesBW(Fig)
    if textLabel!= None:
        pylab.legend(loc='lower left',prop={'size':fontsize2})
    
    if title!= None:
        pylab.title(title, fontsize=fontsize1)
        
    #pylab.title(title,fontsize=24)
    pylab.ylabel('PRECISION [%]',fontsize=fontsize1)
    pylab.xlabel('RECALL [%]',fontsize=fontsize1)
    
    pylab.xlim(0,100)
    pylab.xticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
                      ('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 )
    pylab.ylim(0,100)
    pylab.yticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
                      ('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 )
    pylab.grid(True)
   
    # 
    if type(outFileName) != list:
        pylab.savefig( outFileName )
    else:
        for outFn in outFileName:
            pylab.savefig( outFn )
    if clearFig:
        pylab.close()
        Fig.clear() 
Example #22
Source File: plot.py    From SelfTarget with MIT License 4 votes vote down vote up
def plotCorrelations(all_result_outputs, label='', data_label='', y_label='', plot_label='', plot_scatters=False, oligo_id_str='Oligo ID', val_str = 'Cut Rate', total_reads_str= 'Total Reads', scatter_samples={}, sdims=(0,0), scatter_fig=None, add_leg=True):
    
    datas = [x[0][data_label][0] for x in all_result_outputs]
    sample_names = [shortDirLabel(x[1]) for x in all_result_outputs]
    
    merged_data = pd.merge(datas[0],datas[1],how='inner',on=oligo_id_str, suffixes=['', ' 2'])
    for i, data in enumerate(datas[2:]):
        merged_data = pd.merge(merged_data, data,how='inner',on=oligo_id_str, suffixes=['', ' %d' % (i+3)])
    suffix = lambda i: ' %d' % (i+1) if i > 0 else ''

    N = len(sample_names)
    if plot_scatters: 
        if scatter_fig is None: PL.figure()
        else: PL.figure(scatter_fig.number)
        s_dims = (N,N) if len(scatter_samples) == 0 else sdims
    pcorrs, scorrs = np.zeros((N,N)), np.zeros((N,N))
    for i,label1 in enumerate(sample_names):
        for j,label2 in enumerate(sample_names):
            dvs1, dvs2, ids = merged_data[val_str + suffix(i)], merged_data[val_str + suffix(j)], merged_data[oligo_id_str]
            pcorrs[i,j] = pearsonr(dvs1, dvs2)[0]
            scorrs[i,j] = spearmanr(dvs1, dvs2)[0]
            if plot_scatters:
                if (label1, label2) in scatter_samples: idx = scatter_samples[(label1, label2)]
                elif len(scatter_samples) == 0: idx = i*N+j+1
                else: continue
                PL.subplot(s_dims[0],s_dims[1],idx)
                trs1, trs2 = merged_data[total_reads_str + suffix(i)], merged_data[total_reads_str + suffix(j)]
                for thr in [20,50,100,500,1000]:
                    thr_dvs = [(dv1, dv2,id) for (dv1, dv2, tr1, tr2,id) in zip(dvs1,dvs2,trs1,trs2,ids) if (tr1 >= thr and tr2 >= thr) ]
                    pcorrs[i,j] = pearsonr([x[0] for x in thr_dvs], [x[1] for x in thr_dvs])[0]
                    PL.plot([x[0] for x in thr_dvs],[x[1] for x in thr_dvs],'.', label='>%d Reads' % thr)

                PL.plot([0,100],[0,100],'k--')
                PL.xlabel('K562 Replicate A')
                PL.ylabel('K562 Replicate B')
                if add_leg: PL.legend()
                PL.title('%s (%.2f)' % (y_label, pcorrs[i,j]))
    if plot_scatters: 
        PL.subplots_adjust(left=0.05,right=0.95,top=0.9, bottom=0.1, hspace=0.4)
        PL.show(block=False)
        saveFig(plot_label)

    if not plot_scatters:
        PL.figure(figsize=(10,10))
        #PL.subplot(1,2,1)
        PL.imshow(pcorrs, cmap='hot', vmin = 0.0, vmax = 1.0, interpolation='nearest')
        PL.xticks(range(N),sample_names, rotation='vertical')
        PL.yticks(range(N),sample_names)
        PL.title(y_label + ': Pearson')
        PL.colorbar()
        #PL.subplot(1,2,2)
        #PL.imshow(scorrs, cmap='hot', vmin = 0.0, vmax = 1.0, interpolation='nearest')
        #PL.xticks(range(N),sample_names, rotation='vertical')
        #PL.yticks(range(N),sample_names)
        #PL.title(y_label + ': Spearman')
        #PL.colorbar()
        PL.show(block=False)
        PL.savefig(getPlotDir() + '/%s_%s.png' % (plot_label, sanitizeLabel(label)), bbox_inches='tight') 
Example #23
Source File: helper.py    From KittiSeg with MIT License 4 votes vote down vote up
def plotPrecisionRecall(precision, recall, outFileName, Fig=None, drawCol=1, textLabel = None, title = None, fontsize1 = 24, fontsize2 = 20, linewidth = 3):
    '''
    
    :param precision:
    :param recall:
    :param outFileName:
    :param Fig:
    :param drawCol:
    :param textLabel:
    :param fontsize1:
    :param fontsize2:
    :param linewidth:
    '''
                      
    clearFig = False  
           
    if Fig == None:
        Fig = pylab.figure()
        clearFig = True
        
    #tableString = 'Algo avgprec Fmax prec recall accuracy fpr Q(TonITS)\n'
    linecol = ['g','m','b','c']
    #if we are evaluating SP, then BL is available
    #sectionName = 'Evaluation_'+tag+'PxProb'
    #fullEvalFile = os.path.join(eval_dir,evalName)
    #Precision,Recall,evalString = readEvaluation(fullEvalFile,sectionName,AlgoLabel)

    pylab.plot(100*recall, 100*precision, linewidth=linewidth, color=linecol[drawCol], label=textLabel)


    #writing out PrecRecall curves as graphic
    setFigLinesBW(Fig)
    if textLabel!= None:
        pylab.legend(loc='lower left',prop={'size':fontsize2})
    
    if title!= None:
        pylab.title(title, fontsize=fontsize1)
        
    #pylab.title(title,fontsize=24)
    pylab.ylabel('PRECISION [%]',fontsize=fontsize1)
    pylab.xlabel('RECALL [%]',fontsize=fontsize1)
    
    pylab.xlim(0,100)
    pylab.xticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
                      ('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 )
    pylab.ylim(0,100)
    pylab.yticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
                      ('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 )
    pylab.grid(True)
   
    # 
    if type(outFileName) != list:
        pylab.savefig( outFileName )
    else:
        for outFn in outFileName:
            pylab.savefig( outFn )
    if clearFig:
        pylab.close()
        Fig.clear() 
Example #24
Source File: dataset_float.py    From DEMUD with Apache License 2.0 4 votes vote down vote up
def  plot_item_triangles(self, m, ind, x, r, k, label, U,
                           rerr, feature_weights, band_ind):
    """plot_item_triangles(self, m, ind, x, r, k, label, U,
       rerr, feature_weights, band_ind)

    Plot selection m (index ind, data in x) with triangles to
    mark the largest residual values on band_ind indices
    (i.e., you need to pick them before calling this).

    To use this, define plot_item() in your data set's class
    to call this function instead.
    """

    if x == [] or r == []: 
      print "Error: No data in x and/or r."
      return
  
    pylab.clf()
    # xvals, x, and r need to be column vectors
    pylab.plot(self.xvals, r, 'r-',  linewidth=0.5, label='Expected')
    pylab.plot(self.xvals, x, 'b.-', linewidth=1,   label='Observations')
    # Boost font sizes for axis and tick labels
    pylab.xlabel(self.xlabel) #, fontsize=16)
    pylab.ylabel(self.ylabel) #, fontsize=16)
    '''
    pylab.xticks(fontsize=16)
    pylab.yticks(fontsize=16)
    '''
    pylab.title('DEMUD selection %d (%s), item %d, using K=%d' % \
                (m, label, ind, k))
    pylab.legend(fontsize=10)

    # width of triangles to plot
    width = (self.xvals.max() - self.xvals.min())/100.0
    
    for band in band_ind:
      w = float(self.xvals[band])
      reproj = r[band]
      # Draw a triangle that points up if r > x
      # or down if r < x
      pylab.fill([w-width, w+width, w],
                 [reproj,  reproj,  x[band]],
                 '0.6', zorder=1)

    outdir  = os.path.join('results', self.name)
    if not os.path.exists(outdir):
      os.mkdir(outdir)
    figfile = os.path.join(outdir, 'sel-%d-k-%d-(%s).pdf' % (m, k, label))
    pylab.savefig(figfile)
    print 'Wrote plot to %s' % figfile
    pylab.close() 
Example #25
Source File: helper.py    From KittiSeg with MIT License 4 votes vote down vote up
def plotPrecisionRecall(precision, recall, outFileName, Fig=None, drawCol=1, textLabel = None, title = None, fontsize1 = 24, fontsize2 = 20, linewidth = 3):
    '''
    
    :param precision:
    :param recall:
    :param outFileName:
    :param Fig:
    :param drawCol:
    :param textLabel:
    :param fontsize1:
    :param fontsize2:
    :param linewidth:
    '''
                      
    clearFig = False  
           
    if Fig == None:
        Fig = pylab.figure()
        clearFig = True
        
    #tableString = 'Algo avgprec Fmax prec recall accuracy fpr Q(TonITS)\n'
    linecol = ['g','m','b','c']
    #if we are evaluating SP, then BL is available
    #sectionName = 'Evaluation_'+tag+'PxProb'
    #fullEvalFile = os.path.join(eval_dir,evalName)
    #Precision,Recall,evalString = readEvaluation(fullEvalFile,sectionName,AlgoLabel)

    pylab.plot(100*recall, 100*precision, linewidth=linewidth, color=linecol[drawCol], label=textLabel)


    #writing out PrecRecall curves as graphic
    setFigLinesBW(Fig)
    if textLabel!= None:
        pylab.legend(loc='lower left',prop={'size':fontsize2})
    
    if title!= None:
        pylab.title(title, fontsize=fontsize1)
        
    #pylab.title(title,fontsize=24)
    pylab.ylabel('PRECISION [%]',fontsize=fontsize1)
    pylab.xlabel('RECALL [%]',fontsize=fontsize1)
    
    pylab.xlim(0,100)
    pylab.xticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
                      ('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 )
    pylab.ylim(0,100)
    pylab.yticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
                      ('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 )
    pylab.grid(True)
   
    # 
    if type(outFileName) != list:
        pylab.savefig( outFileName )
    else:
        for outFn in outFileName:
            pylab.savefig( outFn )
    if clearFig:
        pylab.close()
        Fig.clear()