Python matplotlib.pylab.show() Examples

The following are 30 code examples of matplotlib.pylab.show(). 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: models.py    From philo2vec with MIT License 7 votes vote down vote up
def plot(self, words, num_points=None):
        if not num_points:
            num_points = len(words)

        embeddings = self.get_words_embeddings(words)
        tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
        two_d_embeddings = tsne.fit_transform(embeddings[:num_points, :])

        assert two_d_embeddings.shape[0] >= len(words), 'More labels than embeddings'
        pylab.figure(figsize=(15, 15))  # in inches
        for i, label in enumerate(words[:num_points]):
            x, y = two_d_embeddings[i, :]
            pylab.scatter(x, y)
            pylab.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points',
                           ha='right', va='bottom')
        pylab.show() 
Example #2
Source File: bitcoin_price.py    From deep_learning with MIT License 6 votes vote down vote up
def train(self):
        """
        训练
        """
        training_set,test_set, training_inputs, training_target, test_inputs, test_targets = self.getData()

        eth_model = self.buildModel(training_inputs, 1, 20)
        training_target = (training_set["eth_Close"][self.window_len:].values /
                           training_set['eth_Close'][:-self.window_len].values) - 1

        eth_history = eth_model.fit(training_inputs, training_target,
                                    epochs=self.epochs, batch_size=self.batch_size,
                                    verbose=self.verbose, shuffle=True)

        fig, ax1 = plt.subplots(1, 1)
        ax1.plot(eth_history.epoch, eth_history.history['loss'])
        ax1.set_title('Training Loss')
        ax1.set_ylabel('MAE',fontsize=12)
        ax1.set_xlabel('# Epochs',fontsize=12)
        plt.show() 
Example #3
Source File: utils.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_confusion_matrix(cm, genre_list, name, title):
    pylab.clf()
    pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=1.0)
    ax = pylab.axes()
    ax.set_xticks(range(len(genre_list)))
    ax.set_xticklabels(genre_list)
    ax.xaxis.set_ticks_position("bottom")
    ax.set_yticks(range(len(genre_list)))
    ax.set_yticklabels(genre_list)
    pylab.title(title)
    pylab.colorbar()
    pylab.grid(False)
    pylab.show()
    pylab.xlabel('Predicted class')
    pylab.ylabel('True class')
    pylab.grid(False)
    pylab.savefig(
        os.path.join(CHART_DIR, "confusion_matrix_%s.png" % name), bbox_inches="tight") 
Example #4
Source File: interfacemethod.py    From pyiron with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_for_holes(temperature_next, strain_value_lst, nve_run_time_steps, project_parameter, debug_plot=True):
    max_lst, mean_lst = get_voronoi_volume(
        temperature_next=temperature_next,
        strain_lst=strain_value_lst,
        nve_run_time_steps=nve_run_time_steps,
        project_parameter=project_parameter
    )
    if debug_plot:
        plt.plot(strain_value_lst, mean_lst, label='mean')
        plt.plot(strain_value_lst, max_lst, label='max')
        plt.axhline(np.mean(mean_lst) * 2, color='black', linestyle='--')
        plt.legend()
        plt.xlabel('Strain')
        plt.ylabel('Voronoi Volume')
        plt.show()
    return np.array(max_lst) < np.mean(mean_lst) * 2 
Example #5
Source File: imaging.py    From isp with MIT License 6 votes vote down vote up
def __init__(self, name = "unknown", data = -1, is_show = False):
        self.name   = name
        self.data   = data
        self.size   = np.shape(self.data)
        self.is_show = is_show
        self.color_space = "unknown"
        self.bayer_pattern = "unknown"
        self.channel_gain = (1.0, 1.0, 1.0, 1.0)
        self.bit_depth = 0
        self.black_level = (0, 0, 0, 0)
        self.white_level = (1, 1, 1, 1)
        self.color_matrix = [[1., .0, .0],\
                             [.0, 1., .0],\
                             [.0, .0, 1.]] # xyz2cam
        self.min_value = np.min(self.data)
        self.max_value = np.max(self.data)
        self.data_type = self.data.dtype

        # Display image only isShow = True
        if (self.is_show):
            plt.imshow(self.data)
            plt.show() 
Example #6
Source File: test_cca.py    From ibllib with MIT License 6 votes vote down vote up
def test_plotting(self):
        """
        This test is just to document current use in libraries in case of refactoring
        """
        corrs = np.array([.6, .2, .1, .001])
        errs = np.array([.1, .05, .04, .0005])
        fig, ax1 = plt.subplots(1, 1, figsize=(5, 5))
        cca.plot_correlations(corrs, errs, ax=ax1, color='blue')
        cca.plot_correlations(corrs * .1, errs, ax=ax1, color='orange')

    # Shuffle data
    # ...
    # fig, ax1 = plt.subplots(1,1,figsize(10,10))
    # plot_correlations(corrs, ... , ax=ax1, color='blue')
    # plot_correlations(shuffled_coors, ..., ax=ax1, color='red')
    # plt.show() 
Example #7
Source File: rock_paper_scissors.py    From evol with MIT License 6 votes vote down vote up
def plot(self):
        try:
            import pandas as pd
            import matplotlib.pylab as plt
            df = pd.DataFrame(self.history).set_index(['id', 'generation']).fillna(0)
            population_size = sum(df.iloc[0].values)
            n_populations = df.reset_index()['id'].nunique()
            fig, axes = plt.subplots(nrows=n_populations, figsize=(12, 2*n_populations),
                                     sharex='all', sharey='all', squeeze=False)
            for row, (_, pop) in zip(axes, df.groupby('id')):
                ax = row[0]
                pop.reset_index(level='id', drop=True).plot(ax=ax)
                ax.set_ylim([0, population_size])
                ax.set_xlabel('iteration')
                ax.set_ylabel('# w/ preference')
                if n_populations > 1:
                    for i in range(0, df.reset_index().generation.max(), 50):
                        ax.axvline(i)
            plt.show()
        except ImportError:
            print("If you install matplotlib and pandas you will get a pretty plot.") 
Example #8
Source File: signal_spectroscopy.py    From qkit with GNU General Public License v2.0 6 votes vote down vote up
def plot_fit_function(self, num_points=100):
        '''
        try:
            x_coords = np.linspace(self.x_vec[0], self.x_vec[-1], num_points)
        except Exception as message:
            print 'no x axis information specified', message
            return
        '''
        if not qkit.module_available("matplotlib"):
            raise ImportError("matplotlib not found.")
        if self.landscape:
            for trace in self.landscape:
                try:
                    # plt.clear()
                    plt.plot(self.x_vec, trace)
                    plt.fill_between(self.x_vec, trace + float(self.span) / 2, trace - float(self.span) / 2, alpha=0.5)
                except Exception:
                    print('invalid trace...skip')
            plt.axhspan(self.y_vec[0], self.y_vec[-1], facecolor='0.5', alpha=0.5)
            plt.show()
        else:
            print('No trace generated.') 
Example #9
Source File: dataset.py    From Image-Restoration with MIT License 6 votes vote down vote up
def show_pred(images, predictions, ground_truth):
    # choose 10 indice from images and visualize them
    indice = [np.random.randint(0, len(images)) for i in range(40)]
    for i in range(0, 40):
        plt.figure()
        plt.subplot(1, 3, 1)
        plt.tight_layout()
        plt.title('deformed image')
        plt.imshow(images[indice[i]])
        plt.subplot(1, 3, 2)
        plt.tight_layout()
        plt.title('predicted mask')
        plt.imshow(predictions[indice[i]])
        plt.subplot(1, 3, 3)
        plt.tight_layout()
        plt.title('ground truth label')
        plt.imshow(ground_truth[indice[i]])
    plt.show()

# Load Data Science Bowl 2018 training dataset 
Example #10
Source File: spectroscopy.py    From qkit with GNU General Public License v2.0 6 votes vote down vote up
def plot_xz_landscape(self):
        """
        plots the xz landscape, i.e., how your vna frequency span changes with respect to the x vector
        :return: None
        """
        if not qkit.module_available("matplotlib"):
            raise ImportError("matplotlib not found.")

        if self.xzlandscape_func:
            y_values = self.xzlandscape_func(self.spec.x_vec)
            plt.plot(self.spec.x_vec, y_values, 'C1')
            plt.fill_between(self.spec.x_vec, y_values+self.z_span/2., y_values-self.z_span/2., color='C0', alpha=0.5)
            plt.xlim((self.spec.x_vec[0], self.spec.x_vec[-1]))
            plt.ylim((self.xz_freqpoints[0], self.xz_freqpoints[-1]))
            plt.show()
        else:
            print('No xz funcion generated. Use landscape.generate_xz_function') 
Example #11
Source File: utils.py    From ndvr-dml with Apache License 2.0 6 votes vote down vote up
def plot_pr_curve(pr_curve_dml, pr_curve_base, title):
    """
      Function that plots the PR-curve.

      Args:
        pr_curve: the values of precision for each recall value
        title: the title of the plot
    """
    plt.figure(figsize=(16, 9))
    plt.plot(np.arange(0.0, 1.05, 0.05),
             pr_curve_base, color='r', marker='o', linewidth=3, markersize=10)
    plt.plot(np.arange(0.0, 1.05, 0.05),
             pr_curve_dml, color='b', marker='o', linewidth=3, markersize=10)
    plt.grid(True, linestyle='dotted')
    plt.xlabel('Recall', color='k', fontsize=27)
    plt.ylabel('Precision', color='k', fontsize=27)
    plt.yticks(color='k', fontsize=20)
    plt.xticks(color='k', fontsize=20)
    plt.ylim([0.0, 1.05])
    plt.xlim([0.0, 1.0])
    plt.title(title, color='k', fontsize=27)
    plt.tight_layout()
    plt.show() 
Example #12
Source File: menu.py    From trajectory_tracking with MIT License 6 votes vote down vote up
def plot_trajectory(name):
    STEPS = 600
    DELTA = 1 if name != 'linear' else 0.1
    trajectory = create_trajectory(name, STEPS)

    x = [trajectory.get_position_at(i * DELTA).x for i in range(STEPS)]
    y = [trajectory.get_position_at(i * DELTA).y for i in range(STEPS)]

    trajectory_fig, trajectory_plot = plt.subplots(1, 1)
    trajectory_plot.plot(x, y, label='trajectory', lw=3)
    trajectory_plot.set_title(name.title() + ' Trajectory', fontsize=20)
    trajectory_plot.set_xlabel(r'$x{\rm[m]}$', fontsize=18)
    trajectory_plot.set_ylabel(r'$y{\rm[m]}$', fontsize=18)
    trajectory_plot.legend(loc=0)
    trajectory_plot.grid()
    plt.show() 
Example #13
Source File: interfacemethod.py    From pyiron with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_equilibration(temperature_next, strain_lst, nve_run_time_steps, project_parameter, debug_plot=True):
    if debug_plot:
        for strain in strain_lst:
            job_name = get_nve_job_name(
                temperature_next=temperature_next,
                strain=strain,
                steps_lst=project_parameter['nve_run_time_steps_lst'],
                nve_run_time_steps=nve_run_time_steps
            )
            ham_nve = project_parameter['project'].load(job_name)
            plt.plot(ham_nve['output/generic/temperature'], label='strain: ' + str(strain))
            plt.axhline(np.mean(ham_nve['output/generic/temperature'][-20:]), linestyle='--', color='red')
            plt.axvline(range(len(ham_nve['output/generic/temperature']))[-20], linestyle='--', color='black')
            plt.legend()
            plt.xlabel('timestep')
            plt.ylabel('Temperature K')
            plt.legend()
            plt.show() 
Example #14
Source File: BirthMoveTopicModel.py    From refinery with MIT License 6 votes vote down vote up
def viz_missing_docwordfreq_stats(DocWordFreq_emp, DocWordFreq_model):
  from matplotlib import pylab
  DocWordFreq_missing = np.maximum(DocWordFreq_emp - DocWordFreq_model, 0)

  nnzEmp = count_num_nonzero(DocWordFreq_emp)
  nnzMiss = count_num_nonzero(DocWordFreq_missing)
  frac_nzMiss = nnzMiss / float(nnzEmp)

  nzMissPerDoc = np.sum(DocWordFreq_missing > 0, axis=1)
  CDF_nzMissPerDoc = np.sort(nzMissPerDoc)
  nzMissPerWord = np.sum(DocWordFreq_missing > 0, axis=0)
  CDF_nzMissPerWord = np.sort(nzMissPerWord)

  pylab.subplot(1,2,1)
  pylab.plot(CDF_nzMissPerDoc)
  pylab.ylabel('Num Nonzero Entries in Doc')
  pylab.xlabel('Document rank | frac= %.4f'% (frac_nzMiss))
  pylab.subplot(1,2,2)
  pylab.plot(CDF_nzMissPerWord)
  pylab.ylabel('Num Nonzero Entries per Word')
  pylab.xlabel('Word rank')

  pylab.show(block=True) 
Example #15
Source File: kNN.py    From statistical-learning-methods-note with Apache License 2.0 6 votes vote down vote up
def plotKChart(self, misClassDict, saveFigPath):
        kList = []
        misRateList = []
        for k, misClassNum in misClassDict.iteritems():
            kList.append(k)
            misRateList.append(1.0 - 1.0/k*misClassNum)

        fig = plt.figure(saveFigPath)
        plt.plot(kList, misRateList, 'r--')
        plt.title(saveFigPath)
        plt.xlabel('k Num.')
        plt.ylabel('Misclassified Rate')
        plt.legend(saveFigPath)
        plt.grid(True)
        plt.savefig(saveFigPath)
        plt.show()

################################### PART3 TEST ########################################
# 例子 
Example #16
Source File: DeadLeaves.py    From refinery with MIT License 5 votes vote down vote up
def plotImgPatchPrototypes(doShowNow=True):
  from matplotlib import pylab
  pylab.figure()
  for kk in range(K):
    pylab.subplot(2, 4, kk+1)
    Xp = makeImgPatchPrototype(D, kk)
    pylab.imshow(Xp, interpolation='nearest')
  if doShowNow:
    pylab.show() 
Example #17
Source File: TestFromScratchGauss.py    From refinery with MIT License 5 votes vote down vote up
def MakeData(self, K=5, Nperclass=1000):
    PRNG = np.random.RandomState(867)
    sigma = 1e-3
    Xlist = list()
    for k in range(K):
      Xcur = sigma * PRNG.randn(Nperclass, 2)
      Xcur += k
      Xlist.append(Xcur)
    self.Data = XData(np.vstack(Xlist))
    #pylab.plot(self.Data.X[:,0], self.Data.X[:,1], 'k.')
    #pylab.show() 
Example #18
Source File: DeadLeaves.py    From refinery with MIT License 5 votes vote down vote up
def plotTrueCovMats(doShowNow=True):
  from matplotlib import pylab
  pylab.figure()
  for kk in range(K):
    pylab.subplot(2, 4, kk+1)
    pylab.imshow(Sigma[kk], interpolation='nearest')
  if doShowNow:
    pylab.show() 
Example #19
Source File: BirthMoveTopicModel.py    From refinery with MIT License 5 votes vote down vote up
def viz_deletion_sidebyside(model, rmodel, ELBO, rELBO, block=False):
  from ..viz import BarsViz
  from matplotlib import pylab
  pylab.figure()
  h=pylab.subplot(1,2,1)
  BarsViz.plotBarsFromHModel(model, figH=h)
  h=pylab.subplot(1,2,2)
  BarsViz.plotBarsFromHModel(rmodel, figH=h)
  pylab.xlabel("%.3e" % (rELBO - ELBO))
  pylab.show(block=block) 
Example #20
Source File: BirthMoveTopicModel.py    From refinery with MIT License 5 votes vote down vote up
def viz_docwordfreq_sidebyside(P1, P2, title1='', title2='', 
                                vmax=None, aspect=None, block=False):
  from matplotlib import pylab
  pylab.figure()

  if vmax is None:
    vmax = 1.0
    P1limit = np.percentile(P1.flatten(), 97)
    if P2 is not None:
      P2limit = np.percentile(P2.flatten(), 97)
    else:
      P2limit = P1limit
    while vmax > P1limit and vmax > P2limit:
      vmax = 0.8 * vmax

  if aspect is None:
    aspect = float(P1.shape[1])/P1.shape[0]
  pylab.subplot(1, 2, 1)
  pylab.imshow(P1, aspect=aspect, interpolation='nearest', vmin=0, vmax=vmax)
  if len(title1) > 0:
    pylab.title(title1)
  if P2 is not None:
    pylab.subplot(1, 2, 2)
    pylab.imshow(P2, aspect=aspect, interpolation='nearest', vmin=0, vmax=vmax)
    if len(title2) > 0:
      pylab.title(title2)
  pylab.show(block=block) 
Example #21
Source File: OldMergeMove.py    From refinery with MIT License 5 votes vote down vote up
def viz_merge_proposal(curModel, propModel, kA, kB, curEv, propEv):
  ''' Visualize merge proposal (in 2D)
  '''
  from ..viz import GaussViz, BarsViz
  from matplotlib import pylab
  
  fig = pylab.figure()
  h1 = pylab.subplot(1,2,1)
  if curModel.obsModel.__class__.__name__.count('Gauss'):
    GaussViz.plotGauss2DFromHModel(curModel, compsToHighlight=[kA, kB])
  else:
    BarsViz.plotBarsFromHModel(curModel, compsToHighlight=[kA, kB], figH=h1)
  pylab.title( 'Before Merge' )
  pylab.xlabel( 'ELBO=  %.2e' % (curEv) )
    
  h2 = pylab.subplot(1,2,2)
  if curModel.obsModel.__class__.__name__.count('Gauss'):
    GaussViz.plotGauss2DFromHModel(propModel, compsToHighlight=[kA])
  else:
    BarsViz.plotBarsFromHModel(propModel, compsToHighlight=[kA], figH=h2)
  pylab.title( 'After Merge' )
  pylab.xlabel( 'ELBO=  %.2e \n %d' % (propEv, propEv > curEv))
  pylab.show(block=False)
  try: 
    x = raw_input('Press any key to continue / Ctrl-C to quit >>')
  except KeyboardInterrupt:
    import sys
    sys.exit(-1)
  pylab.close() 
Example #22
Source File: dataset.py    From Image-Restoration with MIT License 5 votes vote down vote up
def __call__(self, sample):
        # if sample.keys
        image, label = sample['image'], sample['label']
        # swap color axis because
        # numpy image: H x W x C
        # torch image: C X H X W
        image = np.expand_dims(image, 0)
        label = np.expand_dims(label, 0)
        return {'image': torch.from_numpy(image.astype(np.uint8)),
                'label': torch.from_numpy(label.astype(np.uint8))}

# Helper function to show a batch 
Example #23
Source File: sigsys.py    From scikit-dsp-comm with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def my_psd(x,NFFT=2**10,Fs=1):
    """
    A local version of NumPy's PSD function that returns the plot arrays.

    A mlab.psd wrapper function that returns two ndarrays;
    makes no attempt to auto plot anything.

    Parameters
    ----------
    x : ndarray input signal
    NFFT : a power of two, e.g., 2**10 = 1024
    Fs : the sampling rate in Hz

    Returns
    -------
    Px : ndarray of the power spectrum estimate
    f : ndarray of frequency values
    
    Notes
    -----
    This function makes it easier to overlay spectrum plots because
    you have better control over the axis scaling than when using psd()
    in the autoscale mode.
    
    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> from numpy import log10
    >>> from sk_dsp_comm import sigsys as ss
    >>> x,b, data = ss.NRZ_bits(10000,10)
    >>> Px,f = ss.my_psd(x,2**10,10)
    >>> plt.plot(f, 10*log10(Px))
    >>> plt.ylabel("Power Spectral Density (dB)")
    >>> plt.xlabel("Frequency (Hz)")
    >>> plt.show()
    """
    Px,f = pylab.mlab.psd(x,NFFT,Fs)
    return Px.flatten(), f 
Example #24
Source File: MergeMove.py    From refinery with MIT License 5 votes vote down vote up
def viz_merge_proposal(curModel, propModel, kA, kB, curEv, propEv):
  ''' Visualize merge proposal (in 2D)
  '''
  from ..viz import GaussViz, BarsViz
  from matplotlib import pylab
  
  fig = pylab.figure()
  h1 = pylab.subplot(1,2,1)
  if curModel.obsModel.__class__.__name__.count('Gauss'):
    GaussViz.plotGauss2DFromHModel(curModel, compsToHighlight=[kA, kB])
  else:
    BarsViz.plotBarsFromHModel(curModel, compsToHighlight=[kA, kB], figH=h1)
  pylab.title( 'Before Merge' )
  pylab.xlabel( 'ELBO=  %.2e' % (curEv) )
    
  h2 = pylab.subplot(1,2,2)
  if curModel.obsModel.__class__.__name__.count('Gauss'):
    GaussViz.plotGauss2DFromHModel(propModel, compsToHighlight=[kA])
  else:
    BarsViz.plotBarsFromHModel(propModel, compsToHighlight=[kA], figH=h2)
  pylab.title( 'After Merge' )
  pylab.xlabel( 'ELBO=  %.2e \n %d' % (propEv, propEv > curEv))
  pylab.show(block=False)
  try: 
    x = raw_input('Press any key to continue / Ctrl-C to quit >>')
  except KeyboardInterrupt:
    import sys
    sys.exit(-1)
  pylab.close() 
Example #25
Source File: sigsys.py    From scikit-dsp-comm with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def tri(t,tau):
    """
    Approximation to the triangle pulse Lambda(t/tau).
    
    In this numerical version of Lambda(t/tau) the pulse is active
    over -tau <= t <= tau.
    
    Parameters
    ----------
    t : ndarray of the time axis
    tau : one half the triangle base width
    
    Returns
    -------
    x : ndarray of the signal Lambda(t/tau)
    
    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> from numpy import arange
    >>> from sk_dsp_comm.sigsys import tri
    >>> t = arange(-1,5,.01)
    >>> x = tri(t,1.0)
    >>> plt.plot(t,x)
    >>> plt.show()

    To turn on at t = 1, shift t.

    >>> x = tri(t - 1.0,1.0)
    >>> plt.plot(t,x)
    """
    x = np.zeros(len(t))
    for k,tk in enumerate(t):
        if np.abs(tk) > tau/1.:
            x[k] = 0
        else:
            x[k] = 1 - np.abs(tk)/tau
    return x 
Example #26
Source File: sigsys.py    From scikit-dsp-comm with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def rect(t,tau):
    """
    Approximation to the rectangle pulse Pi(t/tau).
    
    In this numerical version of Pi(t/tau) the pulse is active
    over -tau/2 <= t <= tau/2.
    
    Parameters
    ----------
    t : ndarray of the time axis
    tau : the pulse width
    
    Returns
    -------
    x : ndarray of the signal Pi(t/tau)
    
    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> from numpy import arange
    >>> from sk_dsp_comm.sigsys import rect
    >>> t = arange(-1,5,.01)
    >>> x = rect(t,1.0)
    >>> plt.plot(t,x)
    >>> plt.ylim([0, 1.01])
    >>> plt.show()

    To turn on the pulse at t = 1 shift t.

    >>> x = rect(t - 1.0,1.0)
    >>> plt.plot(t,x)
    >>> plt.ylim([0, 1.01])
    """
    x = np.zeros(len(t))
    for k,tk in enumerate(t):
        if np.abs(tk) > tau/2.:
            x[k] = 0
        else:
            x[k] = 1
    return x 
Example #27
Source File: sigsys.py    From scikit-dsp-comm with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def delta_eps(t,eps):
    """
    Rectangular pulse approximation to impulse function.
    
    Parameters
    ----------
    t : ndarray of time axis
    eps : pulse width
    
    Returns
    -------
    d : ndarray containing the impulse approximation
    
    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> from numpy import arange
    >>> from sk_dsp_comm.sigsys import delta_eps
    >>> t = np.arange(-2,2,.001)
    >>> d = delta_eps(t,.1)
    >>> plt.plot(t,d)
    >>> plt.show()
    """
    d = np.zeros(len(t))
    for k,tt in enumerate(t):
        if abs(tt) <= eps/2.:
            d[k] = 1/float(eps)
    return d 
Example #28
Source File: spectroscopy.py    From qkit with GNU General Public License v2.0 5 votes vote down vote up
def plot_xy_landscape(self):
        """
        Plots the xy landscape(s) (for 3D scan, z-axis (vna) is not plotted
        :return:
        """
        if not qkit.module_available("matplotlib"):
            raise ImportError("matplotlib not found.")

        if self.xylandscapes:
            for i in self.xylandscapes:
                try:
                    arg = np.where((i['x_range'][0] <= self.spec.x_vec) & (self.spec.x_vec <= i['x_range'][1]))
                    x = self.spec.x_vec[arg]
                    t = i['center_points'][arg]
                    plt.plot(x, t, color='C1')
                    if i['blacklist']:
                        plt.fill_between(x, t + i['y_span'] / 2., t - i['y_span'] / 2., color='C3', alpha=0.5)
                    else:
                        plt.fill_between(x, t + i['y_span'] / 2., t - i['y_span'] / 2., color='C0', alpha=0.5)
                except Exception as e:
                    print(e)
                    print('invalid trace...skip')
            plt.axhspan(np.min(self.spec.y_vec), np.max(self.spec.y_vec), facecolor='0.5', alpha=0.5)
            plt.xlim(np.min(self.spec.x_vec), np.max(self.spec.x_vec))
            plt.show()
        else:
            print('No trace generated. Use landscape.generate_xy_function') 
Example #29
Source File: image_rescale.py    From FitML with MIT License 5 votes vote down vote up
def resize_cat(cat):
    cat = scipy.misc.imresize(cat,size=(cat.shape[0]/2,cat.shape[1]/2))
    plt.imshow(cat)
    plt.show() 
Example #30
Source File: image_rescale.py    From FitML with MIT License 5 votes vote down vote up
def show_cat(cat_batch):
    print("cat shape before transfo",cat_batch.shape)
    cat = np.squeeze(cat_batch,axis=0)
    print( "cat.shape", cat.shape)
    plt.imshow(cat)
    plt.show()