Python matplotlib.pylab.text() Examples

The following are 9 code examples of matplotlib.pylab.text(). 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 matplotlib.pylab , or try the search function .
Example #1
Source File: plotter.py    From periodic-table-plotter with MIT License 5 votes vote down vote up
def pettifor(self, xaxis=atomic_number, yaxis=atomic_number,
            label=symbol):
        """
        Create a pettifor map with the specified x- and y-axes.

        Keyword Arguments:
            xaxis, yaxis:
                Function that takes a dict as an input, and returns a number.
                Will plot this data point with the elements symbol at the
                coordinate determined by the xaxis and yaxis functions.

        Examples::

            >>> # Define a function with the desired axis label as the
            >>> # docstring and which returns the x or y coord for the point.
            >>> def eneg2(d):
            >>>     '''Electronegativity squared'''
            >>>     return d['electronegativity']**2
            >>> epd = ElementDataPlotter()
            >>> # then assign that function to an axis
            >>> # (both axes are the atomic number by default)
            >>> epd.pettifor(xaxis=eneg2)
            >>> plt.show()

        """
        x, y = [],[]
        for elt, data in self._elts.items():
            xx = xaxis(data)
            yy = yaxis(data)
            x.append(xx)
            y.append(yy)
            self._ax.text(xx, yy, label(data))
        self._ax.scatter(x, y)
        self._ax.autoscale_view()
        self._ax.set_xlabel(xaxis.__doc__)
        self._ax.set_ylabel(yaxis.__doc__) 
Example #2
Source File: plotter.py    From periodic-table-plotter with MIT License 5 votes vote down vote up
def single_label(self, label, position="top", **kwargs):
        """
        Labels a single Patch. Label position can be set with the "position"
        keyword argument as shown below:
                
                   top
             +------------+
             |            |
             |            |
        left |     1st    | right
             |            |
             |            |
             +------------+
                bottom
        """
        assert isinstance(label, string_types)
        if position == 'top':
            x = self.x + self.dx/2
            y = self.y + self.dy*1.25
            ha, va = 'center', 'bottom'
        elif position == 'bottom':
            x = self.x + self.dx/2
            y = self.y - self.dy*0.25
            ha, va = 'center', 'top'
        elif position == 'left':
            x = self.x - self.dx*0.25
            y = self.y + self.y/2
            ha, va = 'right', 'center'
        elif position == 'right':
            x = self.x + self.dx*1.25
            y = self.y + self.y/2
            ha, va = 'left', 'center'
        else:
            raise ValueError("`position` must be one of:"
                    "'top', 'bottom', 'left', 'right'")
        fontdict = kwargs.get('fontdict', {})
        plt.text(x, y, label, ha=ha, va=va, fontdict=fontdict) 
Example #3
Source File: plotter.py    From periodic-table-plotter with MIT License 5 votes vote down vote up
def double_label(self, labels, position="horizontal", **kwargs):
        """
        Plots 2 colors in a square:
            
                      vertical
                   +-------------+
                   |            /|
                   |   1st    /  |
                   |        /    |
        horizontal |      /      | horizontal
                   |    /        |
                   |  /   2nd    |
                   |/            |
                   +-------------+
                       vertical
        """
        assert len(labels) == 2
        if position == 'horizontal':
            x1 = self.x - self.dx*0.25
            x2 = self.x + self.dx*1.25
            y1 = y2 = self.y + self.dy/2
            ha1, ha2 = 'right', 'left'
            va1 = va2 = 'center'
        elif position == 'vertical':
            x1 = x2 = self.x + self.dx/2
            y1 = self.y + self.dy*1.25
            y2 = self.y - self.dy*0.25
            ha1 = ha2 = 'center'
            va1, va2 = 'bottom', 'top'
        else:
            raise ValueError("`position` must be one of:"
                    "'horizontal', 'vertical'")
        fontdict = kwargs.get('fontdict', {})
        plt.text(x1, y1, labels[0], ha=ha1, va=va1, fontdict=fontdict) 
        plt.text(x2, y2, labels[1], ha=ha2, va=va2, fontdict=fontdict) 
Example #4
Source File: plotter.py    From periodic-table-plotter with MIT License 5 votes vote down vote up
def quadra_label(self, labels, **kwargs):
        """
        Plots 4 values in a square:

                +------+-----+
                |      |     |
        label1  | 1st  | 2nd | label2
                |      |     |
                +------+-----+
                |      |     |
        label4  | 4th  | 3rd | label3
                |      |     |
                +------+-----+

        """
        assert len(labels) == 4
        x1 = x4 = self.x - self.dx*0.25
        x2 = x3 = self.x + self.dx*1.25
        y1 = y2 = self.y + self.dy*0.75
        y3 = y4 = self.y + self.dy*0.25
        ha1 = ha4 = 'right'
        ha2 = ha3 = 'left'
        va = 'center'
        fontdict = kwargs.get('fontdict', {})
        plt.text(x1, y1, labels[0], ha=ha1, va=va, fontdict=fontdict)
        plt.text(x2, y2, labels[1], ha=ha2, va=va, fontdict=fontdict)
        plt.text(x3, y3, labels[2], ha=ha3, va=va, fontdict=fontdict)
        plt.text(x4, y4, labels[3], ha=ha4, va=va, fontdict=fontdict) 
Example #5
Source File: plot_roc.py    From speaker_recognition with Apache License 2.0 5 votes vote down vote up
def plot_roc(score_list, save_dir, plot_name):

    save_path = os.path.join(save_dir, plot_name + ".jpg")
    # ζŒ‰η…§ score ζŽ’εΊ
    threshold_value = sorted([score for score, _ in score_list])

    threshold_num = len(threshold_value)
    accracy_array = np.zeros(threshold_num)
    precision_array = np.zeros(threshold_num)
    TPR_array = np.zeros(threshold_num)
    TNR_array = np.zeros(threshold_num)
    FNR_array = np.zeros(threshold_num)
    FPR_array = np.zeros(threshold_num)

    # calculate all the rates
    for thres in range(threshold_num):
        accracy, precision, TPR, TNR, FNR, FPR = cal_rate(score_list, threshold_value[thres])
        accracy_array[thres] = accracy
        precision_array[thres] = precision
        TPR_array[thres] = TPR
        TNR_array[thres] = TNR
        FNR_array[thres] = FNR
        FPR_array[thres] = FPR

    AUC = np.trapz(TPR_array, FPR_array)
    threshold = np.argmin(abs(FNR_array - FPR_array))
    EER = (FNR_array[threshold] + FPR_array[threshold]) / 2
    # print('EER : %f AUC : %f' % (EER, -AUC))
    plt.plot(FPR_array, TPR_array)

    plt.title('ROC')
    plt.xlabel('FPR')
    plt.ylabel('TPR')
    plt.text(0.2, 0, s="EER :{} AUC :{} Threshold:{}".format(round(EER, 4), round(-AUC, 4),
                                                             round(threshold_value[threshold], 4)), fontsize=10)
    plt.legend()
    plt.savefig(save_path)
    plt.show() 
Example #6
Source File: evaluation.py    From deepecg with MIT License 5 votes vote down vote up
def plot_confusion_matrix(y_true, y_pred, classes, figure_size=(8, 8)):
    """This function plots a confusion matrix."""
    # Compute confusion matrix
    cm = confusion_matrix(y_true, y_pred)
    cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] * 100

    # Build Laussen Labs colormap
    cmap = LinearSegmentedColormap.from_list('laussen_labs_green', ['w', '#43BB9B'], N=256)

    # Setup plot
    plt.figure(figsize=figure_size)

    # Plot confusion matrix
    plt.imshow(cm, interpolation='nearest', cmap=cmap)

    # Modify axes
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=90)
    plt.yticks(tick_marks, classes)
    thresh = cm.max() / 1.5
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, str(np.round(cm[i, j], 2)) + ' %', horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black", fontsize=20)
    plt.xticks(fontsize=16)
    plt.yticks(fontsize=16)
    plt.tight_layout()
    plt.ylabel('True Label', fontsize=25)
    plt.xlabel('Predicted Label', fontsize=25)

    plt.show() 
Example #7
Source File: plotter.py    From periodic-table-plotter with MIT License 4 votes vote down vote up
def make_grid(self, xelts=[], yelts=[], functions=[eneg_diff],
            cmaps='jet', draw=True, **kwargs):
        """
        Plots a grid of squares colored by one or more properties for A-B 
        element combinations. 
        """
        self.set_functions(functions, cmaps=cmaps)

        if not xelts and not yelts:
            elts = set()
            for pair in self._pairs:
                elts |= set(pair)
            xelts = list(elts)
            yelts = list(elts)

        for i, elt1 in enumerate(xelts):
            self._ax.text(i+0.5, 0.25, elt1, 
                          va='bottom', ha='center', rotation='vertical')
            self._ax.text(i+0.5, -len(yelts) - 0.25, elt1, 
                          va='top', ha='center', rotation='vertical')
            for j, elt2 in enumerate(yelts):
                pair = (elt1, elt2)
                data = self._pairs.get(pair, {})
                if isinstance(data, dict):
                    data['pair'] = pair
                if data is None:
                    continue
                vals = [ f(data) for f in self.functions ]
                square = Square(i, -j, dy=-1., data=vals, **kwargs)
                self.add_square(square)

        for j, elt2 in enumerate(yelts):
            self._ax.text(-0.25, -j-0.5, elt2, 
                          va='center', ha='right')
            self._ax.text(len(xelts) + 0.25, -j-0.5, elt2, 
                          va='center', ha='left')

        self._ax.set_xticks([])
        self._ax.set_yticks([])
        if draw:
            self.draw(**kwargs)
        self._ax.autoscale_view() 
Example #8
Source File: plotter.py    From periodic-table-plotter with MIT License 4 votes vote down vote up
def draw(self, colorbars=True, **kwargs):
        """
        Color squares on plot appropriately, and place color bar
        
        Input:
            colorbars - boolean, Whether to print colorbars on figure
        
        Kwargs:
            font - dict, Containing information about the font for element labels
            colorbars - boolean, Whether to print colorbars
            colorbar-options - dict, Containing settings specific for the colorbars
        """
        
        # Plot each set of patches making up the squares, which correspond
        #  to the different properties being plotted
        self.cbars = []
        for coll, cmap, label in zip(self.collections, self.cmaps, self.cbar_labels):
            pc = PatchCollection(coll, cmap=cmap)
            pc.set_array(np.array([ p.value for p in coll ]))
            self._ax.add_collection(pc)

            if colorbars:
                options = {
                        'orientation':'horizontal',
                        'pad':0.05, 'aspect':60
                        }

                options.update(kwargs.get('colorbar_options', {}))
                cbar = plt.colorbar(pc, **options)
                cbar.set_label(label)
                self.cbars.append(cbar)

        # Add label to center of square
        fontdict = kwargs.get('font', {'color':'white'})
        for s in self.squares:
            if not s.label:
                continue
            x = s.x + s.dx/2
            y = s.y + s.dy/2
            self._ax.text(x, y, s.label, ha='center', 
                                         va='center', 
                                         fontdict=fontdict)

        # Plot the guide square
        if self.guide_square:
            self.guide_square.set_labels(self.labels)
            pc = PatchCollection(self.guide_square.patches, match_original=True)
            self._ax.add_collection(pc)
        self._ax.autoscale_view() 
Example #9
Source File: nifti_viewer.py    From cortex_old with GNU General Public License v3.0 4 votes vote down vote up
def save_image(nifti, anat, cluster_dict, out_path, f, image_threshold=2,
               texcol=1, bgcol=0, iscale=2, text=None, **kwargs):
    '''Saves a single nifti image.

    Args:
        nifti (str or nipy.core.api.image.image.Image): nifti file to visualize.
        anat (nipy.core.api.image.image.Image): anatomical nifti file.
        cluster_dict (dict): dictionary of clusters.
        f (int): index.
        image_threshold (float): treshold for `plot_map`.
        texcol (float): text color.
        bgcol (float): background color.
        iscale (float): image scale.
        text (Optional[str]): text for figure.
        **kwargs: extra keyword arguments

    '''
    if isinstance(nifti, str):
        nifti = load_image(nifti)
        feature = nifti.get_data()
    elif isinstance(nifti, nipy.core.image.image.Image):
        feature = nifti.get_data()
    font = {'size': 8}
    rc('font', **font)

    coords = cluster_dict['top_clust']['coords']
    if coords == None:
        return

    feature /= feature.std()
    imax = np.max(np.absolute(feature))
    imin = -imax
    imshow_args = dict(
        vmax=imax,
        vmin=imin,
        alpha=0.7
    )

    coords = ([-coords[0], -coords[1], coords[2]])

    plt.axis('off')
    plt.text(0.05, 0.8, text, horizontalalignment='center',
             color=(texcol, texcol, texcol))

    try:
        plot_map(feature,
                 xyz_affine(nifti),
                 anat=anat.get_data(),
                 anat_affine=xyz_affine(anat),
                 threshold=image_threshold,
                 cut_coords=coords,
                 annotate=False,
                 cmap=cmap,
                 draw_cross=False,
                 **imshow_args)
    except Exception as e:
        return

    plt.savefig(out_path, transparent=True, facecolor=(bgcol, bgcol, bgcol))