Python matplotlib.ticker.FixedFormatter() Examples

The following are 30 code examples of matplotlib.ticker.FixedFormatter(). 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.ticker , or try the search function .
Example #1
Source File: test_figure.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_autofmt_xdate(which):
    date = ['3 Jan 2013', '4 Jan 2013', '5 Jan 2013', '6 Jan 2013',
            '7 Jan 2013', '8 Jan 2013', '9 Jan 2013', '10 Jan 2013',
            '11 Jan 2013', '12 Jan 2013', '13 Jan 2013', '14 Jan 2013']

    time = ['16:44:00', '16:45:00', '16:46:00', '16:47:00', '16:48:00',
            '16:49:00', '16:51:00', '16:52:00', '16:53:00', '16:55:00',
            '16:56:00', '16:57:00']

    angle = 60
    minors = [1, 2, 3, 4, 5, 6, 7]

    x = mdates.datestr2num(date)
    y = mdates.datestr2num(time)

    fig, ax = plt.subplots()

    ax.plot(x, y)
    ax.yaxis_date()
    ax.xaxis_date()

    ax.xaxis.set_minor_locator(AutoMinorLocator(2))
    ax.xaxis.set_minor_formatter(FixedFormatter(minors))

    fig.autofmt_xdate(0.2, angle, 'right', which)

    if which in ('both', 'major', None):
        for label in fig.axes[0].get_xticklabels(False, 'major'):
            assert int(label.get_rotation()) == angle

    if which in ('both', 'minor'):
        for label in fig.axes[0].get_xticklabels(True, 'minor'):
            assert int(label.get_rotation()) == angle 
Example #2
Source File: _visualization_2d.py    From gempy with GNU Lesser General Public License v3.0 5 votes vote down vote up
def plot_section_by_name(self, section_name, show_data=True, show_faults=True, show_topo=True,
                             show_all_data=False, contourplot=True, radius='default', **kwargs):

        if self.model.solutions.sections is None:
            raise AttributeError('no sections for plotting defined')
        if section_name not in self.model._grid.sections.names:
            raise AttributeError(f'Section "{section_name}" is not defined. '
                                 f'Available sections for plotting: {self.model._grid.sections.names}')

        j = np.where(self.model._grid.sections.names == section_name)[0][0]
        l0, l1 = self.model._grid.sections.get_section_args(section_name)
        shape = self.model._grid.sections.resolution[j]

        image = self.model.solutions.sections[0][0][l0:l1].reshape(shape[0], shape[1]).T
        extent = [0, self.model._grid.sections.dist[j][0],
                  self.model._grid.regular_grid.extent[4], self.model._grid.regular_grid.extent[5]]

        if show_data:
            self.plot_section_data(section_name=section_name, show_all_data=show_all_data, radius=radius)

        axes = plt.gca()
        axes.imshow(image, origin='lower', zorder=-100,
                    cmap=self._cmap, norm=self._norm, extent=extent)
        if show_faults and not contourplot:
            self.extract_section_lines(section_name, axes, faults_only=True)
        else:
            self.extract_section_lines(section_name, axes, faults_only=False)
        if show_topo:
            if self.model._grid.topography is not None:
                alpha = kwargs.get('alpha', 1)
                xy = self.make_topography_overlay_4_sections(j)
                axes.fill(xy[:, 0], xy[:, 1], 'k', zorder=10, alpha=alpha)

        labels, axname = self._make_section_xylabels(section_name, len(axes.get_xticklabels()) - 1)
        pos_list = np.linspace(0, self.model._grid.sections.dist[j], len(labels))
        axes.xaxis.set_major_locator(FixedLocator(nbins=len(labels), locs=pos_list))
        axes.xaxis.set_major_formatter(FixedFormatter((labels)))
        axes.set(title=self.model._grid.sections.names[j], xlabel=axname, ylabel='Z') 
Example #3
Source File: _visualization_2d.py    From gempy with GNU Lesser General Public License v3.0 5 votes vote down vote up
def plot_section_scalarfield(self, section_name, sn, levels=50, show_faults=True, show_topo=True, lithback=True):
        if self.model.solutions.sections is None:
            raise AttributeError('no sections for plotting defined')
        if self.model._grid.topography is None:
            show_topo = False
        shapes = self.model._grid.sections.resolution
        fig = plt.figure(figsize=(16, 10))
        axes = fig.add_subplot(1, 1, 1)
        j = np.where(self.model._grid.sections.names == section_name)[0][0]
        l0, l1 = self.model._grid.sections.get_section_args(section_name)
        if show_faults:
            self.extract_section_fault_lines(section_name, zorder=9)

        if show_topo:
            xy = self.make_topography_overlay_4_sections(j)
            axes.fill(xy[:, 0], xy[:, 1], 'k', zorder=10)

        axes.contour(self.model.solutions.sections[1][sn][l0:l1].reshape(shapes[j][0], shapes[j][1]).T,
                     # origin='lower',
                     levels=levels, cmap='autumn', extent=[0, self.model._grid.sections.dist[j],
                                                           self.model._grid.regular_grid.extent[4],
                                                           self.model._grid.regular_grid.extent[5]], zorder=8)
        axes.set_aspect('equal')
        if lithback:
            axes.imshow(self.model.solutions.sections[0][0][l0:l1].reshape(shapes[j][0], shapes[j][1]).T,
                        origin='lower',
                        cmap=self._cmap, norm=self._norm, extent=[0, self.model._grid.sections.dist[j],
                                                                  self.model._grid.regular_grid.extent[4],
                                                                  self.model._grid.regular_grid.extent[5]])

        labels, axname = self._make_section_xylabels(section_name, len(axes.get_xticklabels()))
        pos_list = np.linspace(0, self.model._grid.sections.dist[j], len(labels))
        axes.xaxis.set_major_locator(FixedLocator(nbins=len(labels), locs=pos_list))
        axes.xaxis.set_major_formatter(FixedFormatter((labels)))
        axes.set(title=self.model._grid.sections.names[j], xlabel=axname, ylabel='Z') 
Example #4
Source File: colorbar.py    From CogAlg with MIT License 5 votes vote down vote up
def set_ticklabels(self, ticklabels, update_ticks=True):
        """
        Set tick labels.

        Tick labels are updated immediately unless *update_ticks* is *False*,
        in which case one should call `.update_ticks` explicitly.
        """
        if isinstance(self.locator, ticker.FixedLocator):
            self.formatter = ticker.FixedFormatter(ticklabels)
            if update_ticks:
                self.update_ticks()
        else:
            cbook._warn_external("set_ticks() must have been called.")
        self.stale = True 
Example #5
Source File: test_figure.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_autofmt_xdate(which):
    date = ['3 Jan 2013', '4 Jan 2013', '5 Jan 2013', '6 Jan 2013',
            '7 Jan 2013', '8 Jan 2013', '9 Jan 2013', '10 Jan 2013',
            '11 Jan 2013', '12 Jan 2013', '13 Jan 2013', '14 Jan 2013']

    time = ['16:44:00', '16:45:00', '16:46:00', '16:47:00', '16:48:00',
            '16:49:00', '16:51:00', '16:52:00', '16:53:00', '16:55:00',
            '16:56:00', '16:57:00']

    angle = 60
    minors = [1, 2, 3, 4, 5, 6, 7]

    x = mdates.datestr2num(date)
    y = mdates.datestr2num(time)

    fig, ax = plt.subplots()

    ax.plot(x, y)
    ax.yaxis_date()
    ax.xaxis_date()

    ax.xaxis.set_minor_locator(AutoMinorLocator(2))
    ax.xaxis.set_minor_formatter(FixedFormatter(minors))

    fig.autofmt_xdate(0.2, angle, 'right', which)

    if which in ('both', 'major', None):
        for label in fig.axes[0].get_xticklabels(False, 'major'):
            assert int(label.get_rotation()) == angle

    if which in ('both', 'minor'):
        for label in fig.axes[0].get_xticklabels(True, 'minor'):
            assert int(label.get_rotation()) == angle 
Example #6
Source File: colorbar.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def set_ticklabels(self, ticklabels, update_ticks=True):
        """
        set tick labels. Tick labels are updated immediately unless
        update_ticks is *False*. To manually update the ticks, call
        *update_ticks* method explicitly.
        """
        if isinstance(self.locator, ticker.FixedLocator):
            self.formatter = ticker.FixedFormatter(ticklabels)
            if update_ticks:
                self.update_ticks()
        else:
            warnings.warn("set_ticks() must have been called.")
        self.stale = True 
Example #7
Source File: Plot.py    From Wave-U-Net with MIT License 5 votes vote down vote up
def draw_spectrogram(example_wav="musb_005_angela thomas wade_audio_model_without_context_cut_28234samples_61002samples_93770samples_126538.wav"):
    y, sr = Utils.load(example_wav, sr=None)
    spec = np.abs(librosa.stft(y, 512, 256, 512))
    norm_spec = librosa.power_to_db(spec**2)
    black_time_frames = np.array([28234, 61002, 93770, 126538]) / 256.0

    fig, ax = plt.subplots()
    img = ax.imshow(norm_spec)
    plt.vlines(black_time_frames, [0, 0, 0, 0], [10, 10, 10, 10], colors="red", lw=2, alpha=0.5)
    plt.vlines(black_time_frames, [256, 256, 256, 256], [246, 246, 246, 246], colors="red", lw=2, alpha=0.5)

    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.1)
    plt.colorbar(img, cax=cax)

    ax.xaxis.set_label_position("bottom")
    #ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x * 256.0 / sr))
    #ax.xaxis.set_major_formatter(ticks_x)
    ax.xaxis.set_major_locator(ticker.FixedLocator(([i * sr / 256. for i in range(len(y)//sr + 1)])))
    ax.xaxis.set_major_formatter(ticker.FixedFormatter(([str(i) for i in range(len(y)//sr + 1)])))

    ax.yaxis.set_major_locator(ticker.FixedLocator(([float(i) * 2000.0 / (sr/2.0) * 256. for i in range(6)])))
    ax.yaxis.set_major_formatter(ticker.FixedFormatter([str(i*2) for i in range(6)]))

    ax.set_xlabel("t (s)")
    ax.set_ylabel('f (KHz)')

    fig.set_size_inches(7., 3.)
    fig.savefig("spectrogram_example.pdf", bbox_inches='tight') 
Example #8
Source File: axis.py    From ImageFusion with MIT License 5 votes vote down vote up
def set_ticklabels(self, ticklabels, *args, **kwargs):
        """
        Set the text values of the tick labels. Return a list of Text
        instances.  Use *kwarg* *minor=True* to select minor ticks.
        All other kwargs are used to update the text object properties.
        As for get_ticklabels, label1 (left or bottom) is
        affected for a given tick only if its label1On attribute
        is True, and similarly for label2.  The list of returned
        label text objects consists of all such label1 objects followed
        by all such label2 objects.

        The input *ticklabels* is assumed to match the set of
        tick locations, regardless of the state of label1On and
        label2On.

        ACCEPTS: sequence of strings
        """
        #ticklabels = [str(l) for l in ticklabels]
        minor = kwargs.pop('minor', False)
        if minor:
            self.set_minor_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_minor_ticks()
        else:
            self.set_major_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_major_ticks()

        ret1 = []
        ret2 = []
        for i, tick in enumerate(ticks):
            if i < len(ticklabels):
                if tick.label1On:
                    tick.label1.set_text(ticklabels[i])
                    tick.label1.update(kwargs)
                    ret1.append(tick.label1)
                if tick.label2On:
                    tick.label2.set_text(ticklabels[i])
                    ret2.append(tick.label2)
                    tick.label2.update(kwargs)
        return ret1 + ret2 
Example #9
Source File: colorbar.py    From ImageFusion with MIT License 5 votes vote down vote up
def set_ticklabels(self, ticklabels, update_ticks=True):
        """
        set tick labels. Tick labels are updated immediately unless
        update_ticks is *False*. To manually update the ticks, call
        *update_ticks* method explicitly.
        """
        if isinstance(self.locator, ticker.FixedLocator):
            self.formatter = ticker.FixedFormatter(ticklabels)
            if update_ticks:
                self.update_ticks()
        else:
            warnings.warn("set_ticks() must have been called.") 
Example #10
Source File: test_figure.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_autofmt_xdate(which):
    date = ['3 Jan 2013', '4 Jan 2013', '5 Jan 2013', '6 Jan 2013',
            '7 Jan 2013', '8 Jan 2013', '9 Jan 2013', '10 Jan 2013',
            '11 Jan 2013', '12 Jan 2013', '13 Jan 2013', '14 Jan 2013']

    time = ['16:44:00', '16:45:00', '16:46:00', '16:47:00', '16:48:00',
            '16:49:00', '16:51:00', '16:52:00', '16:53:00', '16:55:00',
            '16:56:00', '16:57:00']

    angle = 60
    minors = [1, 2, 3, 4, 5, 6, 7]

    x = mdates.datestr2num(date)
    y = mdates.datestr2num(time)

    fig, ax = plt.subplots()

    ax.plot(x, y)
    ax.yaxis_date()
    ax.xaxis_date()

    ax.xaxis.set_minor_locator(AutoMinorLocator(2))
    ax.xaxis.set_minor_formatter(FixedFormatter(minors))

    fig.autofmt_xdate(0.2, angle, 'right', which)

    if which in ('both', 'major', None):
        for label in fig.axes[0].get_xticklabels(False, 'major'):
            assert int(label.get_rotation()) == angle

    if which in ('both', 'minor'):
        for label in fig.axes[0].get_xticklabels(True, 'minor'):
            assert int(label.get_rotation()) == angle 
Example #11
Source File: colorbar.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_ticklabels(self, ticklabels, update_ticks=True):
        """
        set tick labels. Tick labels are updated immediately unless
        update_ticks is *False*. To manually update the ticks, call
        *update_ticks* method explicitly.
        """
        if isinstance(self.locator, ticker.FixedLocator):
            self.formatter = ticker.FixedFormatter(ticklabels)
            if update_ticks:
                self.update_ticks()
        else:
            warnings.warn("set_ticks() must have been called.")
        self.stale = True 
Example #12
Source File: colorbar.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def set_ticklabels(self, ticklabels, update_ticks=True):
        """
        set tick labels. Tick labels are updated immediately unless
        update_ticks is *False*. To manually update the ticks, call
        *update_ticks* method explicitly.
        """
        if isinstance(self.locator, ticker.FixedLocator):
            self.formatter = ticker.FixedFormatter(ticklabels)
            if update_ticks:
                self.update_ticks()
        else:
            warnings.warn("set_ticks() must have been called.")
        self.stale = True 
Example #13
Source File: colorbar.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def set_ticklabels(self, ticklabels, update_ticks=True):
        """
        set tick labels. Tick labels are updated immediately unless
        update_ticks is *False*. To manually update the ticks, call
        *update_ticks* method explicitly.
        """
        if isinstance(self.locator, ticker.FixedLocator):
            self.formatter = ticker.FixedFormatter(ticklabels)
            if update_ticks:
                self.update_ticks()
        else:
            warnings.warn("set_ticks() must have been called.")
        self.stale = True 
Example #14
Source File: axis.py    From neural-network-animation with MIT License 5 votes vote down vote up
def set_ticklabels(self, ticklabels, *args, **kwargs):
        """
        Set the text values of the tick labels. Return a list of Text
        instances.  Use *kwarg* *minor=True* to select minor ticks.
        All other kwargs are used to update the text object properties.
        As for get_ticklabels, label1 (left or bottom) is
        affected for a given tick only if its label1On attribute
        is True, and similarly for label2.  The list of returned
        label text objects consists of all such label1 objects followed
        by all such label2 objects.

        The input *ticklabels* is assumed to match the set of
        tick locations, regardless of the state of label1On and
        label2On.

        ACCEPTS: sequence of strings
        """
        #ticklabels = [str(l) for l in ticklabels]
        minor = kwargs.pop('minor', False)
        if minor:
            self.set_minor_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_minor_ticks()
        else:
            self.set_major_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_major_ticks()

        ret1 = []
        ret2 = []
        for i, tick in enumerate(ticks):
            if i < len(ticklabels):
                if tick.label1On:
                    tick.label1.set_text(ticklabels[i])
                    tick.label1.update(kwargs)
                    ret1.append(tick.label1)
                if tick.label2On:
                    tick.label2.set_text(ticklabels[i])
                    ret2.append(tick.label2)
                    tick.label2.update(kwargs)
        return ret1 + ret2 
Example #15
Source File: colorbar.py    From neural-network-animation with MIT License 5 votes vote down vote up
def set_ticklabels(self, ticklabels, update_ticks=True):
        """
        set tick labels. Tick labels are updated immediately unless
        update_ticks is *False*. To manually update the ticks, call
        *update_ticks* method explicitly.
        """
        if isinstance(self.locator, ticker.FixedLocator):
            self.formatter = ticker.FixedFormatter(ticklabels)
            if update_ticks:
                self.update_ticks()
        else:
            warnings.warn("set_ticks() must have been called.") 
Example #16
Source File: axis.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def set_ticklabels(self, ticklabels, *args, **kwargs):
        """
        Set the text values of the tick labels. Return a list of Text
        instances.  Use *kwarg* *minor=True* to select minor ticks.
        All other kwargs are used to update the text object properties.
        As for get_ticklabels, label1 (left or bottom) is
        affected for a given tick only if its label1On attribute
        is True, and similarly for label2.  The list of returned
        label text objects consists of all such label1 objects followed
        by all such label2 objects.

        The input *ticklabels* is assumed to match the set of
        tick locations, regardless of the state of label1On and
        label2On.

        ACCEPTS: sequence of strings
        """
        #ticklabels = [str(l) for l in ticklabels]
        minor = kwargs.pop('minor', False)
        if minor:
            self.set_minor_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_minor_ticks()
        else:
            self.set_major_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_major_ticks()

        ret1 = []
        ret2 = []
        for i, tick in enumerate(ticks):
            if i < len(ticklabels):
                if tick.label1On:
                    tick.label1.set_text(ticklabels[i])
                    tick.label1.update(kwargs)
                    ret1.append(tick.label1)
                if tick.label2On:
                    tick.label2.set_text(ticklabels[i])
                    ret2.append(tick.label2)
                    tick.label2.update(kwargs)
        return ret1 + ret2 
Example #17
Source File: colorbar.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def set_ticklabels(self, ticklabels, update_ticks=True):
        """
        set tick labels. Tick labels are updated immediately unless
        update_ticks is *False*. To manually update the ticks, call
        *update_ticks* method explicitly.
        """
        if isinstance(self.locator, ticker.FixedLocator):
            self.formatter = ticker.FixedFormatter(ticklabels)
            if update_ticks:
                self.update_ticks()
        else:
            warnings.warn("set_ticks() must have been called.") 
Example #18
Source File: colorbar.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def set_ticklabels(self, ticklabels, update_ticks=True):
        """
        Set tick labels.

        Tick labels are updated immediately unless *update_ticks* is *False*,
        in which case one should call `.update_ticks` explicitly.
        """
        if isinstance(self.locator, ticker.FixedLocator):
            self.formatter = ticker.FixedFormatter(ticklabels)
            if update_ticks:
                self.update_ticks()
        else:
            cbook._warn_external("set_ticks() must have been called.")
        self.stale = True 
Example #19
Source File: axis.py    From Computable with MIT License 5 votes vote down vote up
def set_ticklabels(self, ticklabels, *args, **kwargs):
        """
        Set the text values of the tick labels. Return a list of Text
        instances.  Use *kwarg* *minor=True* to select minor ticks.
        All other kwargs are used to update the text object properties.
        As for get_ticklabels, label1 (left or bottom) is
        affected for a given tick only if its label1On attribute
        is True, and similarly for label2.  The list of returned
        label text objects consists of all such label1 objects followed
        by all such label2 objects.

        The input *ticklabels* is assumed to match the set of
        tick locations, regardless of the state of label1On and
        label2On.

        ACCEPTS: sequence of strings
        """
        #ticklabels = [str(l) for l in ticklabels]
        minor = kwargs.pop('minor', False)
        if minor:
            self.set_minor_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_minor_ticks()
        else:
            self.set_major_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_major_ticks()

        ret1 = []
        ret2 = []
        for i, tick in enumerate(ticks):
            if i < len(ticklabels):
                if tick.label1On:
                    tick.label1.set_text(ticklabels[i])
                    tick.label1.update(kwargs)
                    ret1.append(tick.label1)
                if tick.label2On:
                    tick.label2.set_text(ticklabels[i])
                    ret2.append(tick.label2)
                    tick.label2.update(kwargs)
        return ret1 + ret2 
Example #20
Source File: atacorrect_functions.py    From TOBIAS with MIT License 4 votes vote down vote up
def plot_correction(pre_mat, post_mat, title):
	""" Plot comparison of pre-correction and post-correction matrices """

	#Make figure
	fig, ax = plt.subplots()
	fig.suptitle(title, fontsize=16, weight="bold")

	L = pre_mat.shape[1]
	flank = int(L/2.0)		
	xvals = np.arange(L)  # each position corresponds to i in mat
	
	#Customize minor tick labels
	xtick_pos = xvals[:-1] + 0.5
	xtick_labels = list(range(-flank, flank))		#-flank - flank without 0
	ax.xaxis.set_major_locator(ticker.FixedLocator(xvals))
	ax.xaxis.set_major_formatter(ticker.FixedFormatter(xtick_labels))	
	ax.xaxis.set_minor_locator(ticker.FixedLocator(xtick_pos))			#locate minor ticks between major ones (cutsites)
	ax.xaxis.set_minor_formatter(ticker.NullFormatter())
	
	#PWMs for all mats
	pre_pwm = pre_mat
	post_pwm = post_mat

	#Pre correction
	for nuc in range(4):
		yvals = [pre_pwm[nuc, m] for m in range(L)]
		plt.plot(xvals, yvals, linestyle="--", color=colors[nuc], linewidth=1, alpha=0.5)
	
	#Post correction
	for nuc in range(4):
		yvals = [post_pwm[nuc, m] for m in range(L)]
		plt.plot(xvals, yvals, color=colors[nuc], linewidth=2, label=names[nuc])
	
	plt.xlim([0, L-1])
	plt.xlabel('Position from cutsite')
	plt.ylabel('Nucleotide frequency')

	#Set legend
	plt.plot([0],[0], linestyle="--", linewidth=1, color="black", label="pre-correction")
	plt.plot([0],[0], color="black", label="post-correction")
	plt.legend(loc="lower right", prop={'size':6})

	plt.tight_layout()
	fig.subplots_adjust(top=0.88, hspace=0.4)

	return(fig) 
Example #21
Source File: atacorrect_functions.py    From TOBIAS with MIT License 4 votes vote down vote up
def plot_pssm(matrix, title):
	""" Plot pssm in matrix """

	#Make figure
	fig, ax = plt.subplots()
	fig.suptitle(title, fontsize=16, weight="bold")
	
	#Formatting of x axis
	length = matrix.shape[1]
	flank = int(length/2.0)		
	xvals = np.arange(length)  # each position corresponds to i in mat
	
	#Customize minor tick labels
	xtick_pos = xvals[:-1] + 0.5
	xtick_labels = list(range(-flank, flank))
	ax.xaxis.set_major_locator(ticker.FixedLocator(xvals))
	ax.xaxis.set_major_formatter(ticker.FixedFormatter(xtick_labels))	
	ax.xaxis.set_minor_locator(ticker.FixedLocator(xtick_pos))			#locate minor ticks between major ones (cutsites)
	ax.xaxis.set_minor_formatter(ticker.NullFormatter())

	#Make background grid on major ticks
	plt.grid(color='0.8', which="minor", ls="--", axis="x")

	plt.xlim([0, length-1])
	plt.xlabel('Position from cutsite')
	plt.ylabel('PSSM score')

	######## Plot data #######
	#Plot PSSM / bias motif
	for nuc in range(4):
		plt.plot(xvals, matrix[nuc,:], color=colors[nuc], label=names[nuc])

	#Cutsite-line
	plt.axvline(flank-0.5, linewidth=2, color="black", zorder=100)

	#Finish up
	plt.legend(loc="lower right")
	plt.tight_layout()
	fig.subplots_adjust(top=0.88, hspace=0.5)

	return(fig)

#----------------------------------------------------------------------------------------------------# 
Example #22
Source File: visualization_2d.py    From gempy with GNU Lesser General Public License v3.0 4 votes vote down vote up
def add_section(self, section_name=None, cell_number=None, direction='y', ax=None, ax_pos=111,
                    ve=1., **kwargs):

        extent_val = kwargs.get('extent', None)
        self.update_colot_lot()

        if ax is None:
            ax = self.fig.add_subplot(ax_pos)

        if section_name is not None:
            if section_name == 'topography':
                ax.set_title('Geological map')
                ax.set_xlabel('X')
                ax.set_ylabel('Y')
                extent_val = self.model._grid.topography.extent
            else:

                dist = self.model._grid.sections.df.loc[section_name, 'dist']

                extent_val = [0, dist,
                              self.model._grid.regular_grid.extent[4], self.model._grid.regular_grid.extent[5]]

                labels, axname = self._make_section_xylabels(section_name, len(ax.get_xticklabels()) - 2)
                pos_list = np.linspace(0, dist, len(labels))
                ax.xaxis.set_major_locator(FixedLocator(nbins=len(labels), locs=pos_list))
                ax.xaxis.set_major_formatter(FixedFormatter((labels)))
                ax.set(title=section_name, xlabel=axname, ylabel='Z')

        elif cell_number is not None:
            _a, _b, _c, extent_val, x, y = self._slice(direction, cell_number)[:-2]
            ax.set_xlabel(x)
            ax.set_ylabel(y)
            ax.set(title='Cell Number: ' + str(cell_number) + ' Direction: ' + str(direction))

        if extent_val is not None:
            if extent_val[3] < extent_val[2]:  # correct vertical orientation of plot
                ax.invert_yaxis()
            self._aspect = (extent_val[3] - extent_val[2]) / (extent_val[1] - extent_val[0]) / ve
            ax.set_xlim(extent_val[0], extent_val[1])
            ax.set_ylim(extent_val[2], extent_val[3])
        ax.set_aspect('equal')

        # Adding some properties to the axes to make easier to plot
        ax.section_name = section_name
        ax.cell_number = cell_number
        ax.direction = direction
        ax.tick_params(axis='x', labelrotation=30)
        self.axes = np.append(self.axes, ax)
        self.fig.tight_layout()

        return ax 
Example #23
Source File: axis.py    From twitter-stock-recommendation with MIT License 4 votes vote down vote up
def set_ticklabels(self, ticklabels, *args, **kwargs):
        """
        Set the text values of the tick labels. Return a list of Text
        instances.  Use *kwarg* *minor=True* to select minor ticks.
        All other kwargs are used to update the text object properties.
        As for get_ticklabels, label1 (left or bottom) is
        affected for a given tick only if its label1On attribute
        is True, and similarly for label2.  The list of returned
        label text objects consists of all such label1 objects followed
        by all such label2 objects.

        The input *ticklabels* is assumed to match the set of
        tick locations, regardless of the state of label1On and
        label2On.

        ACCEPTS: sequence of strings or Text objects
        """
        get_labels = []
        for t in ticklabels:
            # try calling get_text() to check whether it is Text object
            # if it is Text, get label content
            try:
                get_labels.append(t.get_text())
            # otherwise add the label to the list directly
            except AttributeError:
                get_labels.append(t)
        # replace the ticklabels list with the processed one
        ticklabels = get_labels

        minor = kwargs.pop('minor', False)
        if minor:
            self.set_minor_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_minor_ticks()
        else:
            self.set_major_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_major_ticks()
        ret = []
        for tick_label, tick in zip(ticklabels, ticks):
            # deal with label1
            tick.label1.set_text(tick_label)
            tick.label1.update(kwargs)
            # deal with label2
            tick.label2.set_text(tick_label)
            tick.label2.update(kwargs)
            # only return visible tick labels
            if tick.label1On:
                ret.append(tick.label1)
            if tick.label2On:
                ret.append(tick.label2)

        self.stale = True
        return ret 
Example #24
Source File: utils.py    From CASED-Tensorflow with MIT License 4 votes vote down vote up
def fp_per_scan(logit, label) :
    logit = np.reshape(logit, -1)
    label = np.reshape(label, -1)

    logit = logit[logit >= 0]
    label = label[label >= 0]

    logit = np.where(logit >= 1.0, logit-1, logit)
    label = np.where(label >= 1.0, label-1, label)

    fpr, tpr, th = roc_curve(label, logit, pos_label=1.0)
    negative_samples = np.count_nonzero(label == 0.0)
    fps = fpr * negative_samples


    """
    mean_sens = np.mean(sens_list)
    matplotlib.use('Agg')

    ax = plt.gca()
    plt.plot(fps_itp, sens_itp)
    # https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.grid.html
    plt.xlim(MIN_FROC, MAX_FROC)
    plt.ylim(0, 1.1)
    plt.xlabel('Average number of false positives per scan')
    plt.ylabel('Sensitivity')
    # plt.legend(loc='lower right')
    # plt.legend(loc=9)
    plt.title('Average sensitivity = %.4f' % (mean_sens))

    plt.xscale('log', basex=2)
    ax.xaxis.set_major_formatter(FixedFormatter(fp_list))

    ax.xaxis.set_ticks(fp_list)
    ax.yaxis.set_ticks(np.arange(0, 1.1, 0.1))
    plt.grid(b=True, linestyle='dotted', which='both')
    plt.tight_layout()

    # plt.show()
    plt.savefig('result.png', bbox_inches=0, dpi=300)
    """

    return np.asarray(fps), np.asarray(tpr) 
Example #25
Source File: _visualization_2d.py    From gempy with GNU Lesser General Public License v3.0 4 votes vote down vote up
def plot_all_sections(self, show_data=False, section_names=None, show_topo=True,
                          figsize=(12, 12)):
        if self.model.solutions.sections is None:
            raise AttributeError('no sections for plotting defined')
        if self.model._grid.topography is None:
            show_topo = False
        if section_names is not None:
            if isinstance(section_names, list):
                section_names = np.array(section_names)
        else:
            section_names = self.model._grid.sections.names

        shapes = self.model._grid.sections.resolution
        fig, axes = plt.subplots(nrows=len(section_names), ncols=1, figsize=figsize)
        for i, section in enumerate(section_names):
            j = np.where(self.model._grid.sections.names == section)[0][0]
            l0, l1 = self.model._grid.sections.get_section_args(section)

            self.extract_section_lines(section, axes[i], faults_only=False)

            if show_topo:
                xy = self.make_topography_overlay_4_sections(j)
                axes[i].fill(xy[:, 0], xy[:, 1], 'k', zorder=10)

            # if show_data:
            #    section = str(section)
            #    print(section)
            #    self.plot_section_data(section_name=section)

            axes[i].imshow(self.model.solutions.sections[0][0][l0:l1].reshape(shapes[j][0], shapes[j][1]).T,
                           origin='lower', zorder=-100,
                           cmap=self._cmap, norm=self._norm, extent=[0, self.model._grid.sections.dist[j],
                                                                     self.model._grid.regular_grid.extent[4],
                                                                     self.model._grid.regular_grid.extent[5]])

            labels, axname = self._make_section_xylabels(section, len(axes[i].get_xticklabels()) - 1)
            pos_list = np.linspace(0, self.model._grid.sections.dist[j], len(labels))
            axes[i].xaxis.set_major_locator(FixedLocator(nbins=len(labels), locs=pos_list))
            axes[i].xaxis.set_major_formatter(FixedFormatter((labels)))
            axes[i].set(title=self.model._grid.sections.names[j], xlabel=axname, ylabel='Z')

        fig.tight_layout() 
Example #26
Source File: axis.py    From CogAlg with MIT License 4 votes vote down vote up
def set_ticklabels(self, ticklabels, *args, minor=False, **kwargs):
        r"""
        Set the text values of the tick labels.

        Parameters
        ----------
        ticklabels : sequence of str or of `Text`\s
            List of texts for tick labels; must include values for non-visible
            labels.
        minor : bool
            If True, set minor ticks instead of major ticks.
        **kwargs
            Text properties.

        Returns
        -------
        labels : list of `Text`\s
            For each tick, includes ``tick.label1`` if it is visible, then
            ``tick.label2`` if it is visible, in that order.
        """
        if args:
            cbook.warn_deprecated(
                "3.1", message="Additional positional arguments to "
                "set_ticklabels are ignored, and deprecated since Matplotlib "
                "3.1; passing them will raise a TypeError in Matplotlib 3.3.")
        get_labels = []
        for t in ticklabels:
            # try calling get_text() to check whether it is Text object
            # if it is Text, get label content
            try:
                get_labels.append(t.get_text())
            # otherwise add the label to the list directly
            except AttributeError:
                get_labels.append(t)
        # replace the ticklabels list with the processed one
        ticklabels = get_labels

        if minor:
            self.set_minor_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_minor_ticks()
        else:
            self.set_major_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_major_ticks()
        ret = []
        for tick_label, tick in zip(ticklabels, ticks):
            # deal with label1
            tick.label1.set_text(tick_label)
            tick.label1.update(kwargs)
            # deal with label2
            tick.label2.set_text(tick_label)
            tick.label2.update(kwargs)
            # only return visible tick labels
            if tick.label1.get_visible():
                ret.append(tick.label1)
            if tick.label2.get_visible():
                ret.append(tick.label2)

        self.stale = True
        return ret 
Example #27
Source File: axis.py    From coffeegrindsize with MIT License 4 votes vote down vote up
def set_ticklabels(self, ticklabels, *args, minor=False, **kwargs):
        """
        Set the text values of the tick labels. Return a list of Text
        instances.  Use *kwarg* *minor=True* to select minor ticks.
        All other kwargs are used to update the text object properties.
        As for get_ticklabels, label1 (left or bottom) is
        affected for a given tick only if its label1On attribute
        is True, and similarly for label2.  The list of returned
        label text objects consists of all such label1 objects followed
        by all such label2 objects.

        The input *ticklabels* is assumed to match the set of
        tick locations, regardless of the state of label1On and
        label2On.

        ACCEPTS: sequence of strings or Text objects
        """
        get_labels = []
        for t in ticklabels:
            # try calling get_text() to check whether it is Text object
            # if it is Text, get label content
            try:
                get_labels.append(t.get_text())
            # otherwise add the label to the list directly
            except AttributeError:
                get_labels.append(t)
        # replace the ticklabels list with the processed one
        ticklabels = get_labels

        if minor:
            self.set_minor_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_minor_ticks()
        else:
            self.set_major_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_major_ticks()
        ret = []
        for tick_label, tick in zip(ticklabels, ticks):
            # deal with label1
            tick.label1.set_text(tick_label)
            tick.label1.update(kwargs)
            # deal with label2
            tick.label2.set_text(tick_label)
            tick.label2.update(kwargs)
            # only return visible tick labels
            if tick.label1On:
                ret.append(tick.label1)
            if tick.label2On:
                ret.append(tick.label2)

        self.stale = True
        return ret 
Example #28
Source File: rotational_invariance.py    From 3DGCN with MIT License 4 votes vote down vote up
def draw_example_graph(dataset, trial_path):
    results = []
    with open(trial_path + "/rotation_single_x.csv") as file:
        reader = csv.reader(file)
        for row in reader:
            result = [float(r) for r in row]  # ex [0, 45, 90, 135, 180, 225, 270, 315]
            results.append([*result[len(result) // 2:], *result[:len(result) // 2 + 1]])

    major_tick = MultipleLocator(18)
    major_formatter = FixedFormatter(["", "-180", "-90", "0", "+90", "+180"])
    minor_tick = MultipleLocator(9)

    x = np.arange(len(results[0]))

    # Draw figure
    for j in range(0, min(len(results), 5)):
        if "bace" in trial_path or "hiv" in trial_path:
            plt.figure(figsize=(8, 2.5))
            ax = plt.subplot(1, 1, 1)
            ax.spines['right'].set_visible(False)
            ax.spines['top'].set_visible(False)

            plt.plot(x, results[j], color="#000000", linewidth=2)

            # Left ticks
            ax.xaxis.set_major_locator(major_tick)
            ax.xaxis.set_major_formatter(major_formatter)
            ax.xaxis.set_minor_locator(minor_tick)
            ax.xaxis.set_minor_formatter(NullFormatter())
            plt.ylim(0, 1)
            plt.yticks(np.arange(0, 1.01, 0.5), ("0.0", "0.5", "1.0"))

            fig_name = "../../experiment/figure/ex/rotation_single_{}_{}_x.png".format(dataset, j)
            plt.savefig(fig_name, dpi=600)
            plt.clf()
            print("Saved figure on {}".format(fig_name))

        else:
            # Figure
            plt.figure(figsize=(8, 2.5))
            ax = plt.subplot(1, 1, 1)
            ax.spines['right'].set_visible(False)
            ax.spines['top'].set_visible(False)

            y = results[j]
            mean_y = np.average(y)
            ylim = (mean_y - 1.5, mean_y + 1.5)
            plt.plot(x, y, color="#000000", linewidth=2)

            # Ticks
            ax.xaxis.set_major_locator(major_tick)
            ax.xaxis.set_major_formatter(major_formatter)
            ax.xaxis.set_minor_locator(minor_tick)
            ax.xaxis.set_minor_formatter(NullFormatter())
            plt.ylim(ylim)

            fig_name = "../../experiment/figure/ex/rotation_single_{}_{}_x.png".format(dataset, j)
            plt.savefig(fig_name, dpi=600)
            plt.clf()
            print("Saved figure on {}".format(fig_name)) 
Example #29
Source File: axis.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def set_ticklabels(self, ticklabels, *args, minor=False, **kwargs):
        """
        Set the text values of the tick labels. Return a list of Text
        instances.  Use *kwarg* *minor=True* to select minor ticks.
        All other kwargs are used to update the text object properties.
        As for get_ticklabels, label1 (left or bottom) is
        affected for a given tick only if its label1On attribute
        is True, and similarly for label2.  The list of returned
        label text objects consists of all such label1 objects followed
        by all such label2 objects.

        The input *ticklabels* is assumed to match the set of
        tick locations, regardless of the state of label1On and
        label2On.

        ACCEPTS: sequence of strings or Text objects
        """
        get_labels = []
        for t in ticklabels:
            # try calling get_text() to check whether it is Text object
            # if it is Text, get label content
            try:
                get_labels.append(t.get_text())
            # otherwise add the label to the list directly
            except AttributeError:
                get_labels.append(t)
        # replace the ticklabels list with the processed one
        ticklabels = get_labels

        if minor:
            self.set_minor_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_minor_ticks()
        else:
            self.set_major_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_major_ticks()
        ret = []
        for tick_label, tick in zip(ticklabels, ticks):
            # deal with label1
            tick.label1.set_text(tick_label)
            tick.label1.update(kwargs)
            # deal with label2
            tick.label2.set_text(tick_label)
            tick.label2.update(kwargs)
            # only return visible tick labels
            if tick.label1On:
                ret.append(tick.label1)
            if tick.label2On:
                ret.append(tick.label2)

        self.stale = True
        return ret 
Example #30
Source File: axis.py    From GraphicDesignPatternByPython with MIT License 4 votes vote down vote up
def set_ticklabels(self, ticklabels, *args, minor=False, **kwargs):
        """
        Set the text values of the tick labels. Return a list of Text
        instances.  Use *kwarg* *minor=True* to select minor ticks.
        All other kwargs are used to update the text object properties.
        As for get_ticklabels, label1 (left or bottom) is
        affected for a given tick only if its label1On attribute
        is True, and similarly for label2.  The list of returned
        label text objects consists of all such label1 objects followed
        by all such label2 objects.

        The input *ticklabels* is assumed to match the set of
        tick locations, regardless of the state of label1On and
        label2On.

        ACCEPTS: sequence of strings or Text objects
        """
        get_labels = []
        for t in ticklabels:
            # try calling get_text() to check whether it is Text object
            # if it is Text, get label content
            try:
                get_labels.append(t.get_text())
            # otherwise add the label to the list directly
            except AttributeError:
                get_labels.append(t)
        # replace the ticklabels list with the processed one
        ticklabels = get_labels

        if minor:
            self.set_minor_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_minor_ticks()
        else:
            self.set_major_formatter(mticker.FixedFormatter(ticklabels))
            ticks = self.get_major_ticks()
        ret = []
        for tick_label, tick in zip(ticklabels, ticks):
            # deal with label1
            tick.label1.set_text(tick_label)
            tick.label1.update(kwargs)
            # deal with label2
            tick.label2.set_text(tick_label)
            tick.label2.update(kwargs)
            # only return visible tick labels
            if tick.label1On:
                ret.append(tick.label1)
            if tick.label2On:
                ret.append(tick.label2)

        self.stale = True
        return ret