Python pylab.figure() Examples

The following are 30 code examples for showing how to use pylab.figure(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module pylab , or try the search function .

Example 1
Project: EDeN   Author: fabriziocosta   File: __init__.py    License: MIT License 8 votes vote down vote up
def plot_confusion_matrix(y_true, y_pred, size=None, normalize=False):
    """plot_confusion_matrix."""
    cm = confusion_matrix(y_true, y_pred)
    fmt = "%d"
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        fmt = "%.2f"
    xticklabels = list(sorted(set(y_pred)))
    yticklabels = list(sorted(set(y_true)))
    if size is not None:
        plt.figure(figsize=(size, size))
    heatmap(cm, xlabel='Predicted label', ylabel='True label',
            xticklabels=xticklabels, yticklabels=yticklabels,
            cmap=plt.cm.Blues, fmt=fmt)
    if normalize:
        plt.title("Confusion matrix (norm.)")
    else:
        plt.title("Confusion matrix")
    plt.gca().invert_yaxis() 
Example 2
Project: TOPFARM   Author: DTUWindEnergy   File: plot.py    License: GNU Affero General Public License v3.0 7 votes vote down vote up
def plot_wt_layout(wt_layout, borders=None, depth=None):
    fig = plt.figure(figsize=(6,6), dpi=2000)
    fs = 14
    ax = plt.subplot(111)

    if depth is not None:
        N = 100
        X, Y = plt.meshgrid(plt.linspace(depth[:,0].min(), depth[:,0].max(), N), 
                            plt.linspace(depth[:,1].min(), depth[:,1].max(), N))
        Z = plt.griddata(depth[:,0],depth[:,1],depth[:,2],X,Y, interp='linear')
        plt.contourf(X,Y,Z, label='depth [m]')
        plt.colorbar().set_label('water depth [m]')
    #ax.plot(wt_layout.wt_positions[:,0], wt_layout.wt_positions[:,1], 'or', label='baseline position')
    
    ax.scatter(wt_layout.wt_positions[:,0], wt_layout.wt_positions[:,1], wt_layout._wt_list('rotor_diameter'), label='baseline position')

    if borders is not None:
        ax.plot(borders[:,0], borders[:,1], 'r--', label='border')
        
    ax.set_xlabel('x [m]'); 
    ax.set_ylabel('y [m]')
    ax.axis('equal');
    ax.legend(loc='lower left') 
Example 3
Project: EDeN   Author: fabriziocosta   File: __init__.py    License: MIT License 6 votes vote down vote up
def plot_roc_curve(y_true, y_score, size=None):
    """plot_roc_curve."""
    false_positive_rate, true_positive_rate, thresholds = roc_curve(
        y_true, y_score)
    if size is not None:
        plt.figure(figsize=(size, size))
        plt.axis('equal')
    plt.plot(false_positive_rate, true_positive_rate, lw=2, color='navy')
    plt.plot([0, 1], [0, 1], color='gray', lw=1, linestyle='--')
    plt.xlabel('False positive rate')
    plt.ylabel('True positive rate')
    plt.ylim([-0.05, 1.05])
    plt.xlim([-0.05, 1.05])
    plt.grid()
    plt.title('Receiver operating characteristic AUC={0:0.2f}'.format(
        roc_auc_score(y_true, y_score))) 
Example 4
Project: EDeN   Author: fabriziocosta   File: estimator_utils.py    License: MIT License 6 votes vote down vote up
def plot_learning_curve(train_sizes, train_scores, test_scores):
    """plot_learning_curve."""
    plt.figure(figsize=(15, 5))
    plt.title('Learning Curve')
    plt.xlabel("Training examples")
    plt.ylabel("AUC ROC")
    tr_ys = compute_stats(train_scores)
    te_ys = compute_stats(test_scores)
    plot_stats(train_sizes, tr_ys,
               label='Training score',
               color='navy')
    plot_stats(train_sizes, te_ys,
               label='Cross-validation score',
               color='orange')
    plt.grid(linestyle=":")
    plt.legend(loc="best")
    plt.show() 
Example 5
Project: TOPFARM   Author: DTUWindEnergy   File: plot.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, add_inputs, title='', **kwargs):
        super(OffshorePlot, self).__init__(**kwargs)
        self.fig = plt.figure(num=None, facecolor='w', edgecolor='k') #figsize=(13, 8), dpi=1000
        self.shape_plot = self.fig.add_subplot(121)
        self.objf_plot = self.fig.add_subplot(122)

        self.targname = add_inputs
        self.title = title

        # Adding automatically the inputs
        for i in add_inputs:
            self.add(i, Float(0.0, iotype='in'))

        #sns.set(style="darkgrid")
        #self.pal = sns.dark_palette("skyblue", as_cmap=True)
        plt.rc('lines', linewidth=1)
        plt.ion()
        self.force_execute = True
        if not pa('fig').exists():
            pa('fig').mkdir() 
Example 6
Project: TOPFARM   Author: DTUWindEnergy   File: plot.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def plot_wind_rose(wind_rose):
    fig = plt.figure(figsize=(12,5), dpi=1000)

    # Plotting the wind statistics
    ax1 = plt.subplot(121, polar=True)
    w = 2.*np.pi/len(wind_rose.frequency)
    b = ax1.bar(np.pi/2.0-np.array(wind_rose.wind_directions)/180.*np.pi - w/2.0, 
                np.array(wind_rose.frequency)*100, width=w)

    # Trick to set the right axes (by default it's not oriented as we are used to in the WE community)
    mirror = lambda d: 90.0 - d if d < 90.0 else 360.0 + (90.0 - d)
    ax1.set_xticklabels([u'%d\xb0'%(mirror(d)) for d in linspace(0.0, 360.0,9)[:-1]]);
    ax1.set_title('Wind direction frequency');

    # Plotting the Weibull A parameter
    ax2 = plt.subplot(122, polar=True)
    b = ax2.bar(np.pi/2.0-np.array(wind_rose.wind_directions)/180.*np.pi - w/2.0, 
                np.array(wind_rose.A), width=w)
    ax2.set_xticklabels([u'%d\xb0'%(mirror(d)) for d in linspace(0.0, 360.0,9)[:-1]]);
    ax2.set_title('Weibull A parameter per wind direction sectors'); 
Example 7
Project: recruit   Author: Frank-qlu   File: test_hist_method.py    License: Apache License 2.0 6 votes vote down vote up
def test_hist_legacy(self):
        _check_plot_works(self.ts.hist)
        _check_plot_works(self.ts.hist, grid=False)
        _check_plot_works(self.ts.hist, figsize=(8, 10))
        # _check_plot_works adds an ax so catch warning. see GH #13188
        with tm.assert_produces_warning(UserWarning):
            _check_plot_works(self.ts.hist, by=self.ts.index.month)
        with tm.assert_produces_warning(UserWarning):
            _check_plot_works(self.ts.hist, by=self.ts.index.month, bins=5)

        fig, ax = self.plt.subplots(1, 1)
        _check_plot_works(self.ts.hist, ax=ax)
        _check_plot_works(self.ts.hist, ax=ax, figure=fig)
        _check_plot_works(self.ts.hist, figure=fig)
        tm.close()

        fig, (ax1, ax2) = self.plt.subplots(1, 2)
        _check_plot_works(self.ts.hist, figure=fig, ax=ax1)
        _check_plot_works(self.ts.hist, figure=fig, ax=ax2)

        with pytest.raises(ValueError):
            self.ts.hist(by=self.ts.index, figure=fig) 
Example 8
Project: recruit   Author: Frank-qlu   File: test_hist_method.py    License: Apache License 2.0 6 votes vote down vote up
def test_grouped_hist_multiple_axes(self):
        # GH 6970, GH 7069
        df = self.hist_df

        fig, axes = self.plt.subplots(2, 3)
        returned = df.hist(column=['height', 'weight', 'category'], ax=axes[0])
        self._check_axes_shape(returned, axes_num=3, layout=(1, 3))
        tm.assert_numpy_array_equal(returned, axes[0])
        assert returned[0].figure is fig
        returned = df.hist(by='classroom', ax=axes[1])
        self._check_axes_shape(returned, axes_num=3, layout=(1, 3))
        tm.assert_numpy_array_equal(returned, axes[1])
        assert returned[0].figure is fig

        with pytest.raises(ValueError):
            fig, axes = self.plt.subplots(2, 3)
            # pass different number of axes from required
            axes = df.hist(column='height', ax=axes) 
Example 9
Project: MeshCNN   Author: ranahanocka   File: mesh_viewer.py    License: MIT License 6 votes vote down vote up
def init_plot():
    ax = pl.figure().add_subplot(111, projection='3d')
    # hide axis, thank to
    # https://stackoverflow.com/questions/29041326/3d-plot-with-matplotlib-hide-axes-but-keep-axis-labels/
    ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
    ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
    ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
    # Get rid of the spines
    ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
    ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
    ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
    # Get rid of the ticks
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_zticks([])
    return (ax, [np.inf, -np.inf, np.inf, -np.inf, np.inf, -np.inf]) 
Example 10
Project: bachbot   Author: feynmanliang   File: rnnrbm.py    License: MIT License 6 votes vote down vote up
def generate(self, filename, show=True):
        '''Generate a sample sequence, plot the resulting piano-roll and save
        it as a MIDI file.
        filename : string
            A MIDI file will be created at this location.
        show : boolean
            If True, a piano-roll of the generated sequence will be shown.'''

        piano_roll = self.generate_function()
        midiwrite(filename, piano_roll, self.r, self.dt)
        if show:
            extent = (0, self.dt * len(piano_roll)) + self.r
            pylab.figure()
            pylab.imshow(piano_roll.T, origin='lower', aspect='auto',
                         interpolation='nearest', cmap=pylab.cm.gray_r,
                         extent=extent)
            pylab.xlabel('time (s)')
            pylab.ylabel('MIDI note number')
            pylab.title('generated piano-roll') 
Example 11
Project: unmixing   Author: arthur-e   File: visualize.py    License: MIT License 6 votes vote down vote up
def on_press(self, event):
        if all((self.x0, self.y0)):
            self.x1 = event.xdata
            self.y1 = event.ydata

            # If both corners are defined
            if all((self.x0, self.y0, self.x1, self.y1)):
                self.rect.set_width(self.x1 - self.x0)
                self.rect.set_height(self.y1 - self.y0)
                self.rect.set_xy((self.x0, self.y0))
                self.ax.add_patch(self.rect)
                self.ax.figure.canvas.draw()
                self.on_draw()
                self.on_reset()

        else:
            self.x0 = event.xdata
            self.y0 = event.ydata 
Example 12
Project: vnpy_crypto   Author: birforce   File: test_hist_method.py    License: MIT License 6 votes vote down vote up
def test_hist_legacy(self):
        _check_plot_works(self.ts.hist)
        _check_plot_works(self.ts.hist, grid=False)
        _check_plot_works(self.ts.hist, figsize=(8, 10))
        # _check_plot_works adds an ax so catch warning. see GH #13188
        with tm.assert_produces_warning(UserWarning):
            _check_plot_works(self.ts.hist, by=self.ts.index.month)
        with tm.assert_produces_warning(UserWarning):
            _check_plot_works(self.ts.hist, by=self.ts.index.month, bins=5)

        fig, ax = self.plt.subplots(1, 1)
        _check_plot_works(self.ts.hist, ax=ax)
        _check_plot_works(self.ts.hist, ax=ax, figure=fig)
        _check_plot_works(self.ts.hist, figure=fig)
        tm.close()

        fig, (ax1, ax2) = self.plt.subplots(1, 2)
        _check_plot_works(self.ts.hist, figure=fig, ax=ax1)
        _check_plot_works(self.ts.hist, figure=fig, ax=ax2)

        with pytest.raises(ValueError):
            self.ts.hist(by=self.ts.index, figure=fig) 
Example 13
Project: vnpy_crypto   Author: birforce   File: test_hist_method.py    License: MIT License 6 votes vote down vote up
def test_grouped_hist_multiple_axes(self):
        # GH 6970, GH 7069
        df = self.hist_df

        fig, axes = self.plt.subplots(2, 3)
        returned = df.hist(column=['height', 'weight', 'category'], ax=axes[0])
        self._check_axes_shape(returned, axes_num=3, layout=(1, 3))
        tm.assert_numpy_array_equal(returned, axes[0])
        assert returned[0].figure is fig
        returned = df.hist(by='classroom', ax=axes[1])
        self._check_axes_shape(returned, axes_num=3, layout=(1, 3))
        tm.assert_numpy_array_equal(returned, axes[1])
        assert returned[0].figure is fig

        with pytest.raises(ValueError):
            fig, axes = self.plt.subplots(2, 3)
            # pass different number of axes from required
            axes = df.hist(column='height', ax=axes) 
Example 14
Project: EDeN   Author: fabriziocosta   File: __init__.py    License: MIT License 5 votes vote down vote up
def draw_adjacency_graph(adjacency_matrix,
                         node_color=None,
                         size=10,
                         layout='graphviz',
                         prog='neato',
                         node_size=80,
                         colormap='autumn'):
    """draw_adjacency_graph."""
    graph = nx.from_scipy_sparse_matrix(adjacency_matrix)

    plt.figure(figsize=(size, size))
    plt.grid(False)
    plt.axis('off')

    if layout == 'graphviz':
        pos = nx.graphviz_layout(graph, prog=prog)
    else:
        pos = nx.spring_layout(graph)

    if len(node_color) == 0:
        node_color = 'gray'
    nx.draw_networkx_nodes(graph, pos,
                           node_color=node_color,
                           alpha=0.6,
                           node_size=node_size,
                           cmap=plt.get_cmap(colormap))
    nx.draw_networkx_edges(graph, pos, alpha=0.5)
    plt.show()


# draw a whole set of graphs:: 
Example 15
Project: EDeN   Author: fabriziocosta   File: __init__.py    License: MIT License 5 votes vote down vote up
def draw_graph_row(graphs,
                   index=0,
                   contract=True,
                   n_graphs_per_line=5,
                   size=4,
                   xlim=None,
                   ylim=None,
                   **args):
    """draw_graph_row."""
    dim = len(graphs)
    size_y = size
    size_x = size * n_graphs_per_line * args.get('size_x_to_y_ratio', 1)
    plt.figure(figsize=(size_x, size_y))

    if xlim is not None:
        plt.xlim(xlim)
        plt.ylim(ylim)
    else:
        plt.xlim(xmax=3)

    for i in range(dim):
        plt.subplot(1, n_graphs_per_line, i + 1)
        graph = graphs[i]
        draw_graph(graph,
                   size=None,
                   pos=graph.graph.get('pos_dict', None),
                   **args)
    if args.get('file_name', None) is None:
        plt.show()
    else:
        row_file_name = '%d_' % (index) + args['file_name']
        plt.savefig(row_file_name,
                    bbox_inches='tight',
                    transparent=True,
                    pad_inches=0)
        plt.close() 
Example 16
Project: EDeN   Author: fabriziocosta   File: __init__.py    License: MIT License 5 votes vote down vote up
def dendrogram(data,
               vectorizer,
               method="ward",
               color_threshold=1,
               size=10,
               filename=None):
    """dendrogram.

    "median","centroid","weighted","single","ward","complete","average"
    """
    data = list(data)
    # get labels
    labels = []
    for graph in data:
        label = graph.graph.get('id', None)
        if label:
            labels.append(label)
    # transform input into sparse vectors
    data_matrix = vectorizer.transform(data)

    # labels
    if not labels:
        labels = [str(i) for i in range(data_matrix.shape[0])]

    # embed high dimensional sparse vectors in 2D
    from sklearn import metrics
    from scipy.cluster.hierarchy import linkage, dendrogram
    distance_matrix = metrics.pairwise.pairwise_distances(data_matrix)
    linkage_matrix = linkage(distance_matrix, method=method)
    plt.figure(figsize=(size, size))
    dendrogram(linkage_matrix,
               color_threshold=color_threshold,
               labels=labels,
               orientation='right')
    if filename is not None:
        plt.savefig(filename)
    else:
        plt.show() 
Example 17
Project: EDeN   Author: fabriziocosta   File: __init__.py    License: MIT License 5 votes vote down vote up
def plot_confusion_matrices(y_true, y_pred, size=12):
    """plot_confusion_matrices."""
    plt.figure(figsize=(size, size))
    plt.subplot(121)
    plot_confusion_matrix(y_true, y_pred, normalize=False)
    plt.subplot(122)
    plot_confusion_matrix(y_true, y_pred, normalize=True)
    plt.tight_layout(w_pad=5)
    plt.show() 
Example 18
Project: EDeN   Author: fabriziocosta   File: __init__.py    License: MIT License 5 votes vote down vote up
def plot_aucs(y_true, y_score, size=12):
    """plot_confusion_matrices."""
    plt.figure(figsize=(size, size / 2.0))
    plt.subplot(121, aspect='equal')
    plot_roc_curve(y_true, y_score)
    plt.subplot(122, aspect='equal')
    plot_precision_recall_curve(y_true, y_score)
    plt.tight_layout(w_pad=5)
    plt.show() 
Example 19
Project: IntroToDeepLearning   Author: robb-brown   File: TensorFlowInterface.py    License: MIT License 5 votes vote down vote up
def plotFields(layer,fieldShape=None,channel=None,figOffset=1,cmap=None,padding=0.01):
	# Receptive Fields Summary
	try:
		W = layer.W
	except:
		W = layer
	wp = W.eval().transpose();
	if len(np.shape(wp)) < 4:		# Fully connected layer, has no shape
		fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)	
	else:			# Convolutional layer already has shape
		features, channels, iy, ix = np.shape(wp)
		if channel is not None:
			fields = wp[:,channel,:,:]
		else:
			fields = np.reshape(wp,[features*channels,iy,ix])

	perRow = int(math.floor(math.sqrt(fields.shape[0])))
	perColumn = int(math.ceil(fields.shape[0]/float(perRow)))

	fig = mpl.figure(figOffset); mpl.clf()
	
	# Using image grid
	from mpl_toolkits.axes_grid1 import ImageGrid
	grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
	for i in range(0,np.shape(fields)[0]):
		im = grid[i].imshow(fields[i],cmap=cmap); 

	grid.cbar_axes[0].colorbar(im)
	mpl.title('%s Receptive Fields' % layer.name)
	
	# old way
	# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
	# tiled = []
	# for i in range(0,perColumn*perRow,perColumn):
	# 	tiled.append(np.hstack(fields2[i:i+perColumn]))
	# 
	# tiled = np.vstack(tiled)
	# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
	mpl.figure(figOffset+1); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar() 
Example 20
Project: IntroToDeepLearning   Author: robb-brown   File: TensorFlowInterface.py    License: MIT License 5 votes vote down vote up
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
	# Output summary
	try:
		W = layer.output
	except:
		W = layer
	wp = W.eval(feed_dict=feed_dict);
	if len(np.shape(wp)) < 4:		# Fully connected layer, has no shape
		temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
		fields = np.reshape(temp,[1]+fieldShape)
	else:			# Convolutional layer already has shape
		wp = np.rollaxis(wp,3,0)
		features, channels, iy,ix = np.shape(wp)
		if channel is not None:
			fields = wp[:,channel,:,:]
		else:
			fields = np.reshape(wp,[features*channels,iy,ix])

	perRow = int(math.floor(math.sqrt(fields.shape[0])))
	perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
	fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
	tiled = []
	for i in range(0,perColumn*perRow,perColumn):
		tiled.append(np.hstack(fields2[i:i+perColumn]))

	tiled = np.vstack(tiled)
	if figOffset is not None:
		mpl.figure(figOffset); mpl.clf(); 

	mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar(); 
Example 21
Project: IntroToDeepLearning   Author: robb-brown   File: TensorFlowInterface.py    License: MIT License 5 votes vote down vote up
def plotFields(layer,fieldShape=None,channel=None,maxFields=25,figName='ReceptiveFields',cmap=None,padding=0.01):
	# Receptive Fields Summary
	W = layer.W
	wp = W.eval().transpose();
	if len(np.shape(wp)) < 4:		# Fully connected layer, has no shape
		fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
	else:			# Convolutional layer already has shape
		features, channels, iy, ix = np.shape(wp)
		if channel is not None:
			fields = wp[:,channel,:,:]
		else:
			fields = np.reshape(wp,[features*channels,iy,ix])

	fieldsN = min(fields.shape[0],maxFields)
	perRow = int(math.floor(math.sqrt(fieldsN)))
	perColumn = int(math.ceil(fieldsN/float(perRow)))

	fig = mpl.figure(figName); mpl.clf()

	# Using image grid
	from mpl_toolkits.axes_grid1 import ImageGrid
	grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
	for i in range(0,fieldsN):
		im = grid[i].imshow(fields[i],cmap=cmap);

	grid.cbar_axes[0].colorbar(im)
	mpl.title('%s Receptive Fields' % layer.name)

	# old way
	# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
	# tiled = []
	# for i in range(0,perColumn*perRow,perColumn):
	# 	tiled.append(np.hstack(fields2[i:i+perColumn]))
	#
	# tiled = np.vstack(tiled)
	# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
	mpl.figure(figName+' Total'); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar() 
Example 22
Project: IntroToDeepLearning   Author: robb-brown   File: TensorFlowInterface.py    License: MIT License 5 votes vote down vote up
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
	# Output summary
	W = layer.output
	wp = W.eval(feed_dict=feed_dict);
	if len(np.shape(wp)) < 4:		# Fully connected layer, has no shape
		temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
		fields = np.reshape(temp,[1]+fieldShape)
	else:			# Convolutional layer already has shape
		wp = np.rollaxis(wp,3,0)
		features, channels, iy,ix = np.shape(wp)
		if channel is not None:
			fields = wp[:,channel,:,:]
		else:
			fields = np.reshape(wp,[features*channels,iy,ix])

	perRow = int(math.floor(math.sqrt(fields.shape[0])))
	perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
	fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
	tiled = []
	for i in range(0,perColumn*perRow,perColumn):
		tiled.append(np.hstack(fields2[i:i+perColumn]))

	tiled = np.vstack(tiled)
	if figOffset is not None:
		mpl.figure(figOffset); mpl.clf();

	mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar(); 
Example 23
Project: python-control   Author: python-control   File: controls.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def RootLocus(self, kvect, fig=None, fignum=1, \
                  clear=True, xlim=None, ylim=None, plotstr='-'):
        """Calculate the root locus by finding the roots of 1+k*TF(s)
        where TF is self.num(s)/self.den(s) and each k is an element
        of kvect."""
        if fig is None:
            import pylab
            fig = pylab.figure(fignum)
        if clear:
            fig.clf()
        ax = fig.add_subplot(111)
        mymat = self._RLFindRoots(kvect)
        mymat = self._RLSortRoots(mymat)
        #plot open loop poles
        poles = array(self.den.r)
        ax.plot(real(poles), imag(poles), 'x')
        #plot open loop zeros
        zeros = array(self.num.r)
        if zeros.any():
            ax.plot(real(zeros), imag(zeros), 'o')
        for col in mymat.T:
            ax.plot(real(col), imag(col), plotstr)
        if xlim:
            ax.set_xlim(xlim)
        if ylim:
            ax.set_ylim(ylim)
        ax.set_xlabel('Real')
        ax.set_ylabel('Imaginary')
        return mymat 
Example 24
Project: python-control   Author: python-control   File: controls.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def impulse_response(self, dt=None, maxt=None, fignum=1, \
                         clear=True, amp=1.0, fig=None, \
                         fmt='-', **kwargs):
        """Find the impulse response of the system using
        scipy.signal.impulse.

        The time vector will go from 0 to maxt in steps of dt
        i.e. t=arange(0,maxt,dt).  If dt and maxt are not given, the
        parameters from the TransferFunction instance will be used.

        If clear is True, the figure will be cleared first.
        clear=False could be used to overlay the impulse responses of
        multiple TransferFunction's.

        amp is the amplitude of the impulse input.

        return y, t

        where y is the impulse response of the transfer function and t
        is the time vector."""

        tvect = self.create_tvect(dt=dt, maxt=maxt)
        temptf = amp*self
        tout, yout = temptf.impulse(T=tvect)

        if fig is None:
            if fignum is not None:
                import pylab
                fig = pylab.figure(fignum)
            
        if fig is not None:
            if clear:
                fig.clf()
            ax = fig.add_subplot(111)
            ax.plot(tvect, yout, fmt, **kwargs)
            ax.set_ylabel('Impulse Response')
            ax.set_xlabel('Time (sec)')

        return yout, tout 
Example 25
Project: recruit   Author: Frank-qlu   File: test_hist_method.py    License: Apache License 2.0 5 votes vote down vote up
def test_plot_fails_when_ax_differs_from_figure(self):
        from pylab import figure
        fig1 = figure()
        fig2 = figure()
        ax1 = fig1.add_subplot(111)
        with pytest.raises(AssertionError):
            self.ts.hist(ax=ax1, figure=fig2) 
Example 26
Project: PiScope   Author: ankitaggarwal011   File: PiScope.py    License: MIT License 5 votes vote down vote up
def setup(self, channels):
    print "Setting up the channels..."
    self.channels = channels
    # Setup oscilloscope window
    self.root = Tkinter.Tk()
    self.root.wm_title("PiScope")
    if len(self.channels) == 1:
      # Create x and y axis
      xAchse = pylab.arange(0, 4000, 1)
      yAchse = pylab.array([0]*4000)
      # Create the plot
      fig = pylab.figure(1)
      self.ax = fig.add_subplot(111)
      self.ax.set_title("Oscilloscope")
      self.ax.set_xlabel("Time")
      self.ax.set_ylabel("Amplitude")
      self.ax.axis([0, 4000, 0, 3.5])
    elif len(self.channels) == 2:
      # Create x and y axis
      xAchse = pylab.array([0]*4000)
      yAchse = pylab.array([0]*4000)
      # Create the plot
      fig = pylab.figure(1)
      self.ax = fig.add_subplot(111)
      self.ax.set_title("X-Y Plotter")
      self.ax.set_xlabel("Channel " + str(self.channels[0]))
      self.ax.set_ylabel("Channel " + str(self.channels[1]))
      self.ax.axis([0, 3.5, 0, 3.5])
    self.ax.grid(True)
    self.line1 = self.ax.plot(xAchse, yAchse, '-')
    # Integrate plot on oscilloscope window
    self.drawing = FigureCanvasTkAgg(fig, master=self.root)
    self.drawing.show()
    self.drawing.get_tk_widget().pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
    # Setup navigation tools
    tool = NavigationToolbar2TkAgg(self.drawing, self.root)
    tool.update()
    self.drawing._tkcanvas.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
    return 
Example 27
Project: KittiSeg   Author: MarvinTeichmann   File: helper.py    License: MIT License 5 votes vote down vote up
def setFigLinesBW(fig):
    """
    Take each axes in the figure, and for each line in the axes, make the
    line viewable in black and white.
    """
    for ax in fig.get_axes():
        setAxLinesBW(ax) 
Example 28
Project: KittiSeg   Author: MarvinTeichmann   File: helper.py    License: MIT License 5 votes vote down vote up
def saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16):
    '''
    
    :param data:
    :param outputname:
    :param cmap:
    '''
    aspect_ratio = float(data.shape[1])/data.shape[0]
    fig = pylab.figure()
    Scale = 8
    # add +1 to get axis text
    fig.set_size_inches(Scale*aspect_ratio+1,Scale*1)
    ax = pylab.gca()
    #ax.set_axis_off()
    #fig.add_axes(ax)
    if cmap != None:
        pylab.set_cmap(cmap)
    
    #ax.imshow(data, interpolation='nearest', aspect = 'normal')
    ax.imshow(data, interpolation='nearest')
    
    if rangeXpx == None:
        rangeXpx = (0, data.shape[1])
    
    if rangeZpx == None:
        rangeZpx = (0, data.shape[0])
        
    modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel)
    #plt.savefig(outputname, bbox_inches='tight', dpi = dpi)
    pylab.savefig(outputname, dpi = data.shape[0]/Scale)
    pylab.close()
    fig.clear() 
Example 29
Project: KittiSeg   Author: MarvinTeichmann   File: helper.py    License: MIT License 5 votes vote down vote up
def setFigLinesBW(fig):
    """
    Take each axes in the figure, and for each line in the axes, make the
    line viewable in black and white.
    """
    for ax in fig.get_axes():
        setAxLinesBW(ax) 
Example 30
Project: KittiSeg   Author: MarvinTeichmann   File: helper.py    License: MIT License 5 votes vote down vote up
def setFigLinesBW(fig):
    """
    Take each axes in the figure, and for each line in the axes, make the
    line viewable in black and white.
    """
    for ax in fig.get_axes():
        setAxLinesBW(ax)