Python matplotlib.mlab.normpdf() Examples

The following are 13 code examples of matplotlib.mlab.normpdf(). 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.mlab , or try the search function .
Example #1
Source File: bar-plots.py    From matplotlib-style-gallery with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def histogram_demo(ax):
    # example data
    mu = 100  # mean of distribution
    sigma = 15  # standard deviation of distribution
    x = mu + sigma * np.random.randn(10000)

    num_bins = 50

    # The histogram of the data.
    _, bins, _ = ax.hist(x, num_bins, normed=1, label='data')

    # Add a 'best fit' line.
    y = mlab.normpdf(bins, mu, sigma)
    ax.plot(bins, y, '-s', label='best fit')

    ax.legend()
    ax.set_xlabel('Smarts')
    ax.set_ylabel('Probability')
    ax.set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$') 
Example #2
Source File: qc.py    From SAMRI with GNU General Public License v3.0 6 votes vote down vote up
def plot_t_value_hist(
	img_path='~/ni_data/ofM.dr/l1/as_composite/sub-5703/ses-ofM/sub-5703_ses-ofM_task-EPI_CBV_chr_longSOA_tstat.nii.gz',
	roi_path='~/ni_data/templates/roi/DSURQEc_ctx.nii.gz',
	mask_path='/usr/share/mouse-brain-atlases/dsurqec_200micron_mask.nii',
	save_as='~/qc_tvalues.pdf',
	):
	"""Make t-value histogram plot"""

	f, axarr = plt.subplots(1, sharex=True)

	roi = nib.load(path.expanduser(roi_path))
	roi_data = roi.get_data()
	mask = nib.load(path.expanduser(mask_path))
	mask_data = mask.get_data()
	idx = np.nonzero(np.multiply(roi_data,mask_data))
	img = nib.load(path.expanduser(img_path))
	data = img.get_data()[idx]
	(mu, sigma) = norm.fit(data)
	n, bins, patches = axarr.hist(data,'auto',normed=1, facecolor='green', alpha=0.75)
	y = mlab.normpdf(bins, mu, sigma)

	axarr.plot(bins, y, 'r--', linewidth=2)
	axarr.set_title('Histogram of t-values $\mathrm{(\mu=%.3f,\ \sigma=%.3f}$)' %(mu, sigma))
	axarr.set_xlabel('t-values')
	plt.savefig(path.expanduser(save_as)) 
Example #3
Source File: latent_variables.py    From pyflux with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_z(self,figsize=(15,5)):
        import matplotlib.pyplot as plt
        import seaborn as sns

        if hasattr(self, 'sample'):
            sns.distplot(self.prior.transform(self.sample), rug=False, hist=False,label=self.method + ' estimate of ' + self.name)

        elif hasattr(self, 'value') and hasattr(self, 'std'):
            x = np.linspace(self.value-self.std*3.5,self.value+self.std*3.5,100)
            plt.figure(figsize=figsize)
            if self.prior.transform_name is None:
                plt.plot(x,mlab.normpdf(x,self.value,self.std),label=self.method + ' estimate of ' + self.name)
            else:
                sims = self.prior.transform(np.random.normal(self.value,self.std,100000))
                sns.distplot(sims, rug=False, hist=False,label=self.method + ' estimate of ' + self.name)
            plt.xlabel('Value')
            plt.legend()
            plt.show()

        else:
            raise ValueError("No information on latent variable to plot!") 
Example #4
Source File: burst_plot.py    From FRETBursts with GNU General Public License v2.0 5 votes vote down vote up
def _fitted_E_plot(d, i=0, F=1, no_E=False, ax=None, show_model=True,
                   verbose=False, two_gauss_model=False, lw=2.5, color='k',
                   alpha=0.5, fillcolor=None):
    """Plot a fitted model overlay on a FRET histogram."""
    if ax is None:
        ax2 = gca()
    else:
        ax2 = plt.twinx(ax=ax)
        ax2.grid(False)

    if d.fit_E_curve and show_model:
        x = r_[-0.2:1.21:0.002]
        y = d.fit_E_model(x, d.fit_E_res[i, :])
        scale = F*d.fit_E_model_F[i]
        if two_gauss_model:
            assert d.fit_E_res.shape[1] > 2
            if d.fit_E_res.shape[1] == 5:
                m1, s1, m2, s2, a1 = d.fit_E_res[i, :]
                a2 = (1-a1)
            elif d.fit_E_res.shape[1] == 6:
                m1, s1, a1, m2, s2, a2 = d.fit_E_res[i, :]
            y1 = a1*normpdf(x, m1, s1)
            y2 = a2*normpdf(x, m2, s2)
            ax2.plot(x, scale*y1, ls='--', lw=lw, alpha=alpha, color=color)
            ax2.plot(x, scale*y2, ls='--', lw=lw, alpha=alpha, color=color)
        if fillcolor is None:
            ax2.plot(x, scale*y, lw=lw, alpha=alpha, color=color)
        else:
            ax2.fill_between(x, scale*y, lw=lw, alpha=alpha, edgecolor=color,
                             facecolor=fillcolor, zorder=10)
        if verbose:
            print('Fit Integral:', np.trapz(scale*y, x))

    ax2.axvline(d.E_fit[i], lw=3, color=red, ls='--', alpha=0.6)
    xtext = 0.6 if d.E_fit[i] < 0.6 else 0.2
    if d.nch > 1 and not no_E:
        ax2.text(xtext, 0.81, "CH%d: $E_{fit} = %.3f$" % (i+1, d.E_fit[i]),
                 transform=gca().transAxes, fontsize=16,
                 bbox=dict(boxstyle='round', facecolor='#dedede', alpha=0.5)) 
Example #5
Source File: samples.py    From MDT with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _rerender(self):
        nmr_maps = len(self.maps_to_show)
        if self._show_trace:
            nmr_maps *= 2

        grid = GridSpec(nmr_maps, 1, left=0.04, right=0.96, top=0.94, bottom=0.06, hspace=0.2)

        i = 0
        for map_name in self.maps_to_show:
            samples = self._voxels[map_name]

            if self._sample_indices is not None:
                samples = samples[:, self._sample_indices]

            title = map_name
            if map_name in self.names:
                title = self.names[map_name]

            if isinstance(self._nmr_bins, dict) and map_name in self._nmr_bins:
                nmr_bins = self._nmr_bins[map_name]
            else:
                nmr_bins = self._nmr_bins

            hist_plot = plt.subplot(grid[i])
            try:
                n, bins, patches = hist_plot.hist(np.nan_to_num(samples[self.voxel_ind, :]), nmr_bins, normed=True)
                plt.title(title)
                i += 1

                if self._fit_gaussian:
                    mu, sigma = norm.fit(samples[self.voxel_ind, :])
                    bincenters = 0.5*(bins[1:] + bins[:-1])
                    y = mlab.normpdf(bincenters, mu, sigma)
                    hist_plot.plot(bincenters, y, 'r', linewidth=1)

                if self._show_trace:
                    trace_plot = plt.subplot(grid[i])
                    trace_plot.plot(samples[self.voxel_ind, :])
                    i += 1
            except IndexError:
                pass 
Example #6
Source File: histogramplot.py    From incubator-sdap-nexus with Apache License 2.0 5 votes vote down vote up
def render(d, x, primary, secondary, parameter, norm_and_curve=False):
    fig, ax = plt.subplots()
    fig.suptitle(string.upper("%s vs. %s" % (primary, secondary)), fontsize=14, fontweight='bold')

    n, bins, patches = plt.hist(x, 50, normed=norm_and_curve, facecolor='green', alpha=0.75)

    if norm_and_curve:
        mean = np.mean(x)
        variance = np.var(x)
        sigma = np.sqrt(variance)
        y = mlab.normpdf(bins, mean, sigma)
        l = plt.plot(bins, y, 'r--', linewidth=1)

    ax.set_title('n = %d' % len(x))

    units = PARAMETER_TO_UNITS[parameter] if parameter in PARAMETER_TO_UNITS else PARAMETER_TO_UNITS["sst"]
    ax.set_xlabel("%s - %s %s" % (primary, secondary, units))

    if norm_and_curve:
        ax.set_ylabel("Probability per unit difference")
    else:
        ax.set_ylabel("Frequency")

    plt.grid(True)

    sio = StringIO()
    plt.savefig(sio, format='png')
    d['plot'] = sio.getvalue() 
Example #7
Source File: aggregation.py    From acl2017-interactive_summarizer with Apache License 2.0 5 votes vote down vote up
def plot_distribution(self, mean, sigma, array):
        vlines = [mean-(1*sigma), mean, mean+(1*sigma)]
        for val in vlines:
            plt.axvline(val, color='k', linestyle='--')

        bins = np.linspace(mean-(4*sigma), mean+(4*sigma), 200)
        plt.hist(array, bins, alpha=0.5)

        y = mlab.normpdf(bins, mean, sigma)
        plt.plot(bins, y, 'r--')
        plt.subplots_adjust(left=0.15)
        plt.show()
        print mean, sigma 
Example #8
Source File: aggregation_new.py    From acl2017-interactive_summarizer with Apache License 2.0 5 votes vote down vote up
def plot_distribution(self, mean, sigma, array):
        vlines = [mean-(1*sigma), mean, mean+(1*sigma)]
        for val in vlines:
            plt.axvline(val, color='k', linestyle='--')

        bins = np.linspace(mean-(4*sigma), mean+(4*sigma), 200)
        plt.hist(array, bins, alpha=0.5)

        y = mlab.normpdf(bins, mean, sigma)
        plt.plot(bins, y, 'r--')
        plt.subplots_adjust(left=0.15)
        plt.show()
        print(mean, sigma) 
Example #9
Source File: aggregation_old.py    From acl2017-interactive_summarizer with Apache License 2.0 5 votes vote down vote up
def plot_distribution(self, mean, sigma, array):
        vlines = [mean-(1*sigma), mean, mean+(1*sigma)]
        for val in vlines:
            plt.axvline(val, color='k', linestyle='--')

        bins = np.linspace(mean-(4*sigma), mean+(4*sigma), 200)
        plt.hist(array, bins, alpha=0.5)

        y = mlab.normpdf(bins, mean, sigma)
        plt.plot(bins, y, 'r--')
        plt.subplots_adjust(left=0.15)
        plt.show()
        print mean, sigma 
Example #10
Source File: latent_variables.py    From pyflux with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_z(self,indices=None,figsize=(15,5),loc=1):
        import matplotlib.pyplot as plt
        import matplotlib.mlab as mlab
        import seaborn as sns

        plt.figure(figsize=figsize) 
        for z in range(1,len(self.z_list)+1):
            if indices is not None and z-1 not in indices:
                continue
            else:
                if hasattr(self.z_list[z-1], 'sample'):
                    sns.distplot(self.z_list[z-1].prior.transform(self.z_list[z-1].sample), rug=False, hist=False,label=self.z_list[z-1].method + ' estimate of ' + self.z_list[z-1].name)

                elif hasattr(self.z_list[z-1], 'value') and hasattr(self.z_list[z-1], 'std'): 

                    if self.z_list[z-1].prior.transform_name is None:
                        x = np.linspace(self.z_list[z-1].value-self.z_list[z-1].std*3.5,self.z_list[z-1].value+self.z_list[z-1].std*3.5,100)
                        plt.plot(x,mlab.normpdf(x,self.z_list[z-1].value,self.z_list[z-1].std),label=self.z_list[z-1].method + ' estimate of ' + self.z_list[z-1].name)
                    else:
                        sims = self.z_list[z-1].prior.transform(np.random.normal(self.z_list[z-1].value,self.z_list[z-1].std,100000))
                        sns.distplot(sims, rug=False, hist=False,label=self.z_list[z-1].method + ' estimate of ' + self.z_list[z-1].name)


                else:
                    raise ValueError("No information on latent variable to plot!")        

        plt.xlabel('Value')
        plt.ylabel('Frequency')
        plt.title('Latent Variable Plot')
        plt.legend(loc=1)
        plt.show() 
Example #11
Source File: spectre.py    From myScripts with GNU General Public License v2.0 5 votes vote down vote up
def makeSpectre(transitions, sigma, step):
    """ Build a spectrum from transitions energies. For each transitions a gaussian
    function of width sigma is added in order to mimick natural broadening.
    
        :param transitions: list of transitions for readTransitions()
        :type transititions: list
        :param sigma: gaussian width in eV
        :type sigma: float
        :param step: number of absissa value
        :type step: int
        :return: absissa and spectrum value in this order
        :rtype: list, list
    
    """

    # max and min transition energies
    minval = min([val[0] for val in transitions]) - 5.0 * sigma
    maxval = max([val[0] for val in transitions]) + 5.0 * sigma
 
    # points
    npts   = int((maxval - minval) / step) + 1

    # absice
    eneval = sp.linspace(minval, maxval, npts)

    spectre = sp.zeros(npts)
    for trans in transitions:
        spectre += trans[2] * normpdf(eneval, trans[0], sigma)

    return eneval, spectre 
Example #12
Source File: impedances_clustering.py    From GridCal with GNU General Public License v3.0 5 votes vote down vote up
def plot_normal(ax, arr):
    """

    :param ax:
    :param mu:
    :param variance:
    :return:
    """
    mu = arr.mean()
    variance = arr.var()
    sigma = math.sqrt(variance)
    x = np.linspace(mu - 6 * sigma, mu + 6 * sigma, 100)

    if mu != 0 and sigma != 0:
        ax.plot(x, mlab.normpdf(x, mu, sigma)) 
Example #13
Source File: plot.py    From ANTsPy with Apache License 2.0 4 votes vote down vote up
def plot_hist(
    image,
    threshold=0.0,
    fit_line=False,
    normfreq=True,
    ## plot label arguments
    title=None,
    grid=True,
    xlabel=None,
    ylabel=None,
    ## other plot arguments
    facecolor="green",
    alpha=0.75,
):
    """
    Plot a histogram from an ANTsImage

    Arguments
    ---------
    image : ANTsImage
        image from which histogram will be created
    """
    img_arr = image.numpy().flatten()
    img_arr = img_arr[np.abs(img_arr) > threshold]

    if normfreq != False:
        normfreq = 1.0 if normfreq == True else normfreq
    n, bins, patches = plt.hist(
        img_arr, 50, normed=normfreq, facecolor=facecolor, alpha=alpha
    )

    if fit_line:
        # add a 'best fit' line
        y = mlab.normpdf(bins, img_arr.mean(), img_arr.std())
        l = plt.plot(bins, y, "r--", linewidth=1)

    if xlabel is not None:
        plt.xlabel(xlabel)
    if ylabel is not None:
        plt.ylabel(ylabel)
    if title is not None:
        plt.title(title)

    plt.grid(grid)
    plt.show()