Python matplotlib.pylab.subplot() Examples

The following are 30 code examples of matplotlib.pylab.subplot(). 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: 07_dqn_distrib.py    From Deep-Reinforcement-Learning-Hands-On with MIT License 6 votes vote down vote up
def save_transition_images(batch_size, predicted, projected, next_distr, dones, rewards, save_prefix):
    for batch_idx in range(batch_size):
        is_done = dones[batch_idx]
        reward = rewards[batch_idx]
        plt.clf()
        p = np.arange(Vmin, Vmax + DELTA_Z, DELTA_Z)
        plt.subplot(3, 1, 1)
        plt.bar(p, predicted[batch_idx], width=0.5)
        plt.title("Predicted")
        plt.subplot(3, 1, 2)
        plt.bar(p, projected[batch_idx], width=0.5)
        plt.title("Projected")
        plt.subplot(3, 1, 3)
        plt.bar(p, next_distr[batch_idx], width=0.5)
        plt.title("Next state")
        suffix = ""
        if reward != 0.0:
            suffix = suffix + "_%.0f" % reward
        if is_done:
            suffix = suffix + "_done"
        plt.savefig("%s_%02d%s.png" % (save_prefix, batch_idx, suffix)) 
Example #2
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 #3
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 #4
Source File: mean_plotter.py    From visual_dynamics with MIT License 6 votes vote down vote up
def __init__(self, fig, gs, label='mean', color='black', alpha=1.0, min_itr=10):
        self._fig = fig
        self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs)
        self._ax = plt.subplot(self._gs[0])

        self._label = label
        self._color = color
        self._alpha = alpha
        self._min_itr = min_itr

        self._ts = np.empty((1, 0))
        self._data_mean = np.empty((1, 0))
        self._plots_mean = self._ax.plot([], [], '-x', markeredgewidth=1.0,
                color=self._color, alpha=1.0, label=self._label)[0]

        self._ax.set_xlim(0-0.5, self._min_itr+0.5)
        self._ax.set_ylim(0, 1)
        self._ax.minorticks_on()
        self._ax.legend(loc='upper right', bbox_to_anchor=(1, 1))

        self._init = False

        self._fig.canvas.draw()
        self._fig.canvas.flush_events()   # Fixes bug with Qt4Agg backend 
Example #5
Source File: loss_plotter.py    From visual_dynamics with MIT License 6 votes vote down vote up
def __init__(self, fig, gs, format_strings=None, format_dicts=None, labels=None, xlabel=None, ylabel=None, yscale='linear'):
        self._fig = fig
        self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs)
        self._ax = plt.subplot(self._gs[0])

        self._labels = labels or []
        self._format_strings = format_strings or []
        self._format_dicts = format_dicts or []

        self._ax.set_xlabel(xlabel or 'iteration')
        self._ax.set_ylabel(ylabel or 'loss')
        self._ax.set_yscale(yscale or 'linear')
        self._ax.minorticks_on()

        self._plots = []

        self._fig.canvas.draw()
        self._fig.canvas.flush_events()   # Fixes bug with Qt4Agg backend 
Example #6
Source File: arrow_plotter.py    From visual_dynamics with MIT License 6 votes vote down vote up
def __init__(self, fig, gs, labels=None, limits=None):
        self._fig = fig
        self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs)
        self._ax = plt.subplot(self._gs[0])
        self._arrow = None
        if labels:
            if len(labels) == 2:
                self._ax.set_xlabel(labels[0])
                self._ax.set_ylabel(labels[1])
            else:
                raise ValueError("invalid labels %r" % labels)
        if limits:
            if len(limits) == 2 and \
                    len(limits[0]) == 2 and \
                    len(limits[1]) == 2:
                self._ax.set_xlim([limits[0][0], limits[1][0]])
                self._ax.set_ylim([limits[0][1], limits[1][1]])
            else:
                raise ValueError("invalid limits %r" % limits)
        self._fig.canvas.draw()
        self._fig.canvas.flush_events()   # Fixes bug with Qt4Agg backend 
Example #7
Source File: demo_ui.py    From spriteworld with Apache License 2.0 6 votes vote down vote up
def __init__(self):
    self.rewards = 10 * [np.nan]
    self.rewards_bounds = [-10, 10]
    self.last_success = None

    plt.ion()
    self._fig = plt.figure(
        figsize=(9, 12), num='Spriteworld', facecolor='white')
    gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
    self._ax_image = plt.subplot(gs[0])
    self._ax_image.axis('off')

    self._ax_scalar = plt.subplot(gs[1])
    self._ax_scalar.spines['right'].set_visible(False)
    self._ax_scalar.spines['top'].set_visible(False)
    self._ax_scalar.xaxis.set_ticks_position('bottom')
    self._ax_scalar.yaxis.set_ticks_position('left')
    self._setup_callbacks() 
Example #8
Source File: 07_dqn_distrib.py    From Deep-Reinforcement-Learning-Hands-On with MIT License 6 votes vote down vote up
def save_state_images(frame_idx, states, net, device="cpu", max_states=200):
    ofs = 0
    p = np.arange(Vmin, Vmax + DELTA_Z, DELTA_Z)
    for batch in np.array_split(states, 64):
        states_v = torch.tensor(batch).to(device)
        action_prob = net.apply_softmax(net(states_v)).data.cpu().numpy()
        batch_size, num_actions, _ = action_prob.shape
        for batch_idx in range(batch_size):
            plt.clf()
            for action_idx in range(num_actions):
                plt.subplot(num_actions, 1, action_idx+1)
                plt.bar(p, action_prob[batch_idx, action_idx], width=0.5)
            plt.savefig("states/%05d_%08d.png" % (ofs + batch_idx, frame_idx))
        ofs += batch_size
        if ofs >= max_states:
            break 
Example #9
Source File: plotlib.py    From incubator-sdap-nexus with Apache License 2.0 5 votes vote down vote up
def plotVtecAndJasonTracks(gtcFiles, outFile=None, names=None, makeFigure=True, show=False, **options):
    """Plot GAIM climate and assim VTEC versus JASON using at least two 'gc' files.
    First file is usually climate file, and rest are assim files.
    """
    ensureItems(options, {'title': 'GAIM vs. JASON for '+gtcFiles[0], \
                          'xlabel': 'Geographic Latitude (deg)', 'ylabel': 'VTEC (TECU)'})
    if 'show' in options:
        show = True
        del options['show']
    M.subplot(211)
    gtcFile = gtcFiles.pop(0)
    name = 'clim_'
    if names: name = names.pop(0)
    specs = [(gtcFile, 'latitude:2,jason:6,gim__:8,%s:13,iri__:10' % name)]
    name = 'assim'
    for i, gtcFile in enumerate(gtcFiles):
        label = name
        if len(gtcFiles) > 1: label += str(i+1)
        specs.append( (gtcFile, 'latitude:2,%s:13' % label) )
    plotColumns(specs, rmsDiffFrom='jason', floatFormat='%5.1f', **options)
    M.legend()
    
    M.subplot(212)
    options.update({'title': 'JASON Track Plot', 'xlabel': 'Longitude (deg)', 'ylabel': 'Latitude (deg)'})
    fields = N.array([map(floatOrMiss, line.split()) for line in open(gtcFiles[0], 'r')])
    lons = fields[:,2]; lats = fields[:,1]
    marksOnMap(lons, lats, show=show, **options)
    if outFile: M.savefig(outFile) 
Example #10
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 #11
Source File: BarsViz.py    From refinery with MIT License 5 votes vote down vote up
def plotExampleBarsDocs(Data, docIDsToPlot=None,
                              vmax=None, nDocToPlot=9, doShowNow=True):
    pylab.figure()
    V = Data.vocab_size
    sqrtV = int(np.sqrt(V))
    assert np.allclose(sqrtV * sqrtV, V)
    if docIDsToPlot is not None:
      nDocToPlot = len(docIDsToPlot)
    else:
      docIDsToPlot = np.random.choice(Data.nDoc, size=nDocToPlot, replace=False)
    nRows = np.floor(np.sqrt(nDocToPlot))
    nCols = np.ceil(nDocToPlot / nRows)
    if vmax is None:
      DocWordArr = Data.to_sparse_docword_matrix().toarray()
      vmax = int(np.max(np.percentile(DocWordArr, 98, axis=0)))
      
    for plotPos, docID in enumerate(docIDsToPlot):
        # Parse current document
        start,stop = Data.doc_range[docID,:]
        wIDs = Data.word_id[start:stop]
        wCts = Data.word_count[start:stop]
        docWordHist = np.zeros(V)
        docWordHist[wIDs] = wCts
        squareIm = np.reshape(docWordHist, (np.sqrt(V), np.sqrt(V)))

        pylab.subplot(nRows, nCols, plotPos)
        pylab.imshow(squareIm, interpolation='nearest', vmin=0, vmax=vmax)
    if doShowNow:
      pylab.show() 
Example #12
Source File: dataset.py    From UNet-pytorch with MIT License 5 votes vote down vote up
def show_batch(sample_batched):
    """Show image with landmarks for a batch of samples."""
    images_batch, masks_batch = sample_batched['image'].numpy().astype(np.uint8), sample_batched['mask'].numpy().astype(np.bool)
    batch_size = len(images_batch)
    for i in range(batch_size):
        plt.figure()
        plt.subplot(1, 2, 1)
        plt.tight_layout()
        plt.imshow(images_batch[i].transpose((1, 2, 0)))
        plt.subplot(1, 2, 2)
        plt.tight_layout()
        plt.imshow(np.squeeze(masks_batch[i].transpose((1, 2, 0))))

# Load Data Science Bowl 2018 training dataset 
Example #13
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 #14
Source File: make_dataset.py    From DeepLearningImplementations with MIT License 5 votes vote down vote up
def check_HDF5(size=64):
    """
    Plot images with landmarks to check the processing
    """

    # Get hdf5 file
    hdf5_file = os.path.join(data_dir, "CelebA_%s_data.h5" % size)

    with h5py.File(hdf5_file, "r") as hf:
        data_color = hf["training_color_data"]
        data_lab = hf["training_lab_data"]
        data_black = hf["training_black_data"]
        for i in range(data_color.shape[0]):
            fig = plt.figure()
            gs = gridspec.GridSpec(3, 1)
            for k in range(3):
                ax = plt.subplot(gs[k])
                if k == 0:
                    img = data_color[i, :, :, :].transpose(1,2,0)
                    ax.imshow(img)
                elif k == 1:
                    img = data_lab[i, :, :, :].transpose(1,2,0)
                    img = color.lab2rgb(img)
                    ax.imshow(img)
                elif k == 2:
                    img = data_black[i, 0, :, :] / 255.
                    ax.imshow(img, cmap="gray")
            gs.tight_layout(fig)
            plt.show()
            plt.clf()
            plt.close() 
Example #15
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 #16
Source File: BirthMove.py    From refinery with MIT License 5 votes vote down vote up
def viz_birth_proposal_2D(curModel, newModel, ktarget, freshCompIDs,
                          title1='Before Birth',
                          title2='After Birth'):
  ''' Create before/after visualization of a birth move (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=ktarget)
  else:
    BarsViz.plotBarsFromHModel(curModel, compsToHighlight=ktarget, figH=h1)
  pylab.title(title1)
    
  h2 = pylab.subplot(1,2,2)
  if curModel.obsModel.__class__.__name__.count('Gauss'):
    GaussViz.plotGauss2DFromHModel(newModel, compsToHighlight=freshCompIDs)
  else:
    BarsViz.plotBarsFromHModel(newModel, compsToHighlight=freshCompIDs, figH=h2)
  pylab.title(title2)
  pylab.show(block=False)
  try: 
    x = raw_input('Press any key to continue >>')
  except KeyboardInterrupt:
    import sys
    sys.exit(-1)
  pylab.close() 
Example #17
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 #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: 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 #20
Source File: utils.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 5 votes vote down vote up
def plot_feat_hist(data_name_list, filename=None):
    pylab.clf()
    num_rows = 1 + (len(data_name_list) - 1) / 2
    num_cols = 1 if len(data_name_list) == 1 else 2
    pylab.figure(figsize=(5 * num_cols, 4 * num_rows))

    for i in range(num_rows):
        for j in range(num_cols):
            pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j)
            x, name = data_name_list[i * num_cols + j]
            pylab.title(name)
            pylab.xlabel('Value')
            pylab.ylabel('Density')
            # the histogram of the data
            max_val = np.max(x)
            if max_val <= 1.0:
                bins = 50
            elif max_val > 50:
                bins = 50
            else:
                bins = max_val
            n, bins, patches = pylab.hist(
                x, bins=bins, normed=1, facecolor='green', alpha=0.75)

            pylab.grid(True)

    if not filename:
        filename = "feat_hist_%s.png" % name

    pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight") 
Example #21
Source File: getFoodContourNN.py    From tierpsy-tracker with MIT License 5 votes vote down vote up
def get_food_prob(mask_file, model, max_bgnd_images = 2, _is_debug = False, resizing_size = DFLT_RESIZING_SIZE):    
    '''
    Predict the food probability for each pixel using a pretrained u-net model.
    '''
    
    with tables.File(mask_file, 'r') as fid:
        if not '/full_data' in fid:
            raise ValueError('The mask file {} does not content the /full_data dataset.'.format(mask_file)) 
            
        bgnd_o = fid.get_node('/full_data')[:max_bgnd_images]
        
        assert bgnd_o.ndim == 3
        if bgnd_o.shape[0] > 1:
            bgnd = [np.max(bgnd_o[i:i+1], axis=0) for i in range(bgnd_o.shape[0]-1)] 
        else:
            bgnd = [np.squeeze(bgnd_o)]
        
        min_size = min(bgnd[0].shape)
        resize_factor = min(resizing_size, min_size)/min_size
        dsize = tuple(int(x*resize_factor) for x in bgnd[0].shape[::-1])
        
        bgnd_s = [cv2.resize(x, dsize) for x in bgnd]
        for b_img in bgnd_s:
            Y_pred = get_unet_prediction(b_img, model, n_flips=1)
            
            if _is_debug:
                import matplotlib.pylab as plt
                plt.figure()
                plt.subplot(1,2,1)
                plt.imshow(b_img, cmap='gray')
                plt.subplot(1, 2,2)    
                plt.imshow(Y_pred, interpolation='none')
        
        original_size = bgnd[0].shape
        return Y_pred, original_size, bgnd_s 
Example #22
Source File: io_methods.py    From signaltrain with GNU General Public License v3.0 5 votes vote down vote up
def plot_valdata(x_val_cuda, knobs_val_cuda, y_val_cuda, y_val_hat_cuda, effect, \
	epoch, loss_val, file_prefix='val_data', num_plots=50, target_size=None):

	x_size = len(x_val_cuda.data.cpu().numpy()[0])
	if target_size is None:
		y_size = len(y_val_cuda.data.cpu().numpy()[0])
	else:
		y_size = target_size
	t_small = range(x_size-y_size, x_size)
	for plot_i in range(0, num_plots):
		x_val = x_val_cuda.data.cpu().numpy()
		knobs_w = effect.knobs_wc( knobs_val_cuda.data.cpu().numpy()[plot_i,:] )
		plt.figure(plot_i,figsize=(6,8))
		titlestr = f'{effect.name} Val data, epoch {epoch+1}, loss_val = {loss_val.item():.3e}\n'
		for i in range(len(effect.knob_names)):
		    titlestr += f'{effect.knob_names[i]} = {knobs_w[i]:.2f}'
		    if i < len(effect.knob_names)-1: titlestr += ', '
		plt.suptitle(titlestr)
		plt.subplot(3, 1, 1)
		plt.plot(x_val[plot_i, :], 'b', label='Input')
		plt.ylim(-1,1)
		plt.xlim(0,x_size)
		plt.legend()
		plt.subplot(3, 1, 2)
		y_val = y_val_cuda.data.cpu().numpy()
		plt.plot(t_small, y_val[plot_i, -y_size:], 'r', label='Target')
		plt.xlim(0,x_size)
		plt.ylim(-1,1)
		plt.legend()
		plt.subplot(3, 1, 3)
		plt.plot(t_small, y_val[plot_i, -y_size:], 'r', label='Target')
		y_val_hat = y_val_hat_cuda.data.cpu().numpy()
		plt.plot(t_small, y_val_hat[plot_i, -y_size:], c=(0,0.5,0,0.85), label='Predicted')
		plt.ylim(-1,1)
		plt.xlim(0,x_size)
		plt.legend()
		filename = file_prefix + '_' + str(plot_i) + '.png'
		savefig(filename)
	return 
Example #23
Source File: utils.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 5 votes vote down vote up
def plot_feat_hist(data_name_list, filename=None):
    pylab.clf()
    num_rows = 1 + (len(data_name_list) - 1) / 2
    num_cols = 1 if len(data_name_list) == 1 else 2
    pylab.figure(figsize=(5 * num_cols, 4 * num_rows))

    for i in range(num_rows):
        for j in range(num_cols):
            pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j)
            x, name = data_name_list[i * num_cols + j]
            pylab.title(name)
            pylab.xlabel('Value')
            pylab.ylabel('Density')
            # the histogram of the data
            max_val = np.max(x)
            if max_val <= 1.0:
                bins = 50
            elif max_val > 50:
                bins = 50
            else:
                bins = max_val
            n, bins, patches = pylab.hist(
                x, bins=bins, normed=1, facecolor='green', alpha=0.75)

            pylab.grid(True)

    if not filename:
        filename = "feat_hist_%s.png" % name

    pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight") 
Example #24
Source File: utils.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 5 votes vote down vote up
def plot_feat_hist(data_name_list, filename=None):
    if len(data_name_list) > 1:
        assert filename is not None

    pylab.figure(num=None, figsize=(8, 6))
    num_rows = int(1 + (len(data_name_list) - 1) / 2)
    num_cols = int(1 if len(data_name_list) == 1 else 2)
    pylab.figure(figsize=(5 * num_cols, 4 * num_rows))

    for i in range(num_rows):
        for j in range(num_cols):
            pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j)
            x, name = data_name_list[i * num_cols + j]
            pylab.title(name)
            pylab.xlabel('Value')
            pylab.ylabel('Fraction')
            # the histogram of the data
            max_val = np.max(x)
            if max_val <= 1.0:
                bins = 50
            elif max_val > 50:
                bins = 50
            else:
                bins = max_val
            n, bins, patches = pylab.hist(
                x, bins=bins, normed=1, alpha=0.75)

            pylab.grid(True)

    if not filename:
        filename = "feat_hist_%s.png" % name.replace(" ", "_")

    pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight") 
Example #25
Source File: plot.py    From POT with MIT License 5 votes vote down vote up
def plot1D_mat(a, b, M, title=''):
    """ Plot matrix M  with the source and target 1D distribution

    Creates a subplot with the source distribution a on the left and
    target distribution b on the tot. The matrix M is shown in between.


    Parameters
    ----------
    a : ndarray, shape (na,)
        Source distribution
    b : ndarray, shape (nb,)
        Target distribution
    M : ndarray, shape (na, nb)
        Matrix to plot
    """
    na, nb = M.shape

    gs = gridspec.GridSpec(3, 3)

    xa = np.arange(na)
    xb = np.arange(nb)

    ax1 = pl.subplot(gs[0, 1:])
    pl.plot(xb, b, 'r', label='Target distribution')
    pl.yticks(())
    pl.title(title)

    ax2 = pl.subplot(gs[1:, 0])
    pl.plot(a, xa, 'b', label='Source distribution')
    pl.gca().invert_xaxis()
    pl.gca().invert_yaxis()
    pl.xticks(())

    pl.subplot(gs[1:, 1:], sharex=ax1, sharey=ax2)
    pl.imshow(M, interpolation='nearest')
    pl.axis('off')

    pl.xlim((0, nb))
    pl.tight_layout()
    pl.subplots_adjust(wspace=0., hspace=0.2) 
Example #26
Source File: plotter_3d.py    From visual_dynamics with MIT License 5 votes vote down vote up
def __init__(self, fig, gs, num_plots, rows=None, cols=None):
        if cols is None:
            cols = int(np.floor(np.sqrt(num_plots)))
        if rows is None:
            rows = int(np.ceil(float(num_plots)/cols))
        assert num_plots <= rows*cols, 'Too many plots to put into gridspec.'

        self._fig = fig
        self._gs = gridspec.GridSpecFromSubplotSpec(8, 1, subplot_spec=gs)
        self._gs_legend = self._gs[0:1, 0]
        self._gs_plot   = self._gs[1:8, 0]

        self._ax_legend = plt.subplot(self._gs_legend)
        self._ax_legend.get_xaxis().set_visible(False)
        self._ax_legend.get_yaxis().set_visible(False)

        self._gs_plots = gridspec.GridSpecFromSubplotSpec(rows, cols, subplot_spec=self._gs_plot)
        self._axarr = [plt.subplot(self._gs_plots[i], projection='3d') for i in range(num_plots)]
        self._lims = [None for i in range(num_plots)]
        self._plots = [[] for i in range(num_plots)]

        for ax in self._axarr:
            ax.tick_params(pad=0)
            ax.locator_params(nbins=5)
            for item in (ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()):
                item.set_fontsize(10)

        self._fig.canvas.draw()
        self._fig.canvas.flush_events()   # Fixes bug with Qt4Agg backend 
Example #27
Source File: realtime_plotter.py    From visual_dynamics with MIT License 5 votes vote down vote up
def __init__(self, fig, gs, time_window=500, labels=None, alphas=None):
        self._fig = fig
        self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs)
        self._ax = plt.subplot(self._gs[0])

        self._time_window = time_window
        self._labels = labels
        self._alphas = alphas
        self._init = False

        if self._labels:
            self.init(len(self._labels))

        self._fig.canvas.draw()
        self._fig.canvas.flush_events()   # Fixes bug with Qt4Agg backend 
Example #28
Source File: dds_parallel_plot.py    From spotpy with MIT License 5 votes vote down vote up
def subplot(data, name, ylabel):
    fig = plt.figure(figsize=(20, 6))
    ax = plt.subplot(111)
    rep_labels = [str(j) for j in reps]
    x_pos = [i for i, _ in enumerate(rep_labels)]
    X = np.arange(len(data))
    ax_plot = ax.bar(x_pos, data, color=color_map(data_normalizer(data)), width=0.45)

    plt.xticks(x_pos, rep_labels)
    plt.xlabel("Repetitions")
    plt.ylabel(ylabel)

    autolabel(ax, ax_plot)
    plt.savefig(name + ".png") 
Example #29
Source File: time_alignment_plotting_tools.py    From hand_eye_calibration with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_angular_velocities(title,
                            angular_velocities,
                            angular_velocities_filtered,
                            block=True):
  fig = plt.figure()

  title_position = 1.05

  fig.suptitle(title, fontsize='24')

  a1 = plt.subplot(1, 2, 1)
  a1.set_title(
      "Angular Velocities Before Filtering \nvx [red], vy [green], vz [blue]",
      y=title_position)
  plt.plot(angular_velocities[:, 0], c='r')
  plt.plot(angular_velocities[:, 1], c='g')
  plt.plot(angular_velocities[:, 2], c='b')

  a2 = plt.subplot(1, 2, 2)
  a2.set_title(
      "Angular Velocities After Filtering \nvx [red], vy [green], vz [blue]", y=title_position)
  plt.plot(angular_velocities_filtered[:, 0], c='r')
  plt.plot(angular_velocities_filtered[:, 1], c='g')
  plt.plot(angular_velocities_filtered[:, 2], c='b')

  plt.subplots_adjust(left=0.025, right=0.975, top=0.8, bottom=0.05)

  if plt.get_backend() == 'TkAgg':
    mng = plt.get_current_fig_manager()
    max_size = mng.window.maxsize()
    max_size = (max_size[0], max_size[1] * 0.45)
    mng.resize(*max_size)
  plt.show(block=block) 
Example #30
Source File: dataset.py    From Image-Restoration with MIT License 5 votes vote down vote up
def show_batch(sample_batched):
    """Show image with landmarks for a batch of samples."""
    images_batch, masks_batch = sample_batched['image'].numpy().astype(np.uint8), sample_batched['mask'].numpy().astype(np.bool)
    batch_size = len(images_batch)
    for i in range(batch_size):
        plt.figure()
        plt.subplot(1, 2, 1)
        plt.tight_layout()
        plt.imshow(images_batch[i].transpose((1, 2, 0)))
        plt.subplot(1, 2, 2)
        plt.tight_layout()
        plt.imshow(np.squeeze(masks_batch[i].transpose((1, 2, 0))))