Python matplotlib.pyplot.spy() Examples

The following are code examples for showing how to use matplotlib.pyplot.spy(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: tools   Author: Olsthoorn   File: mfgrid.py    GNU General Public License v3.0 6 votes vote down vote up
def test_inpoly(self):
        x = np.linspace(0., 100, 101)
        y = np.linspace(100, 0., 101)
        pgcoords = [(30, 0), (80, 50), (10, 80)]

        # individual inpoly function
        plt.spy(self.inpoly(x, y, pgcoords))
        plt.show()

        z = np.array([1, 0])
        gr = self.Grid(x, y, z)

        # grid_method inpoly
        plt.spy(gr.inpoly(pgcoords))
        plt.show()
        return True 
Example 2
Project: mesher   Author: Chrismarsh   File: permutation_tools.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_mat_connectivity(A,filename,**kwargs):
    """Plot the spy view of the connectivity matrix
    - TODO kwargs can be used to get values to pass into matplotlib functions"""

    fig=plt.figure(figsize=(18,16), dpi= 80)
    plt.spy(A,markersize=0.05)
    Nnz = A.nnz
    Nrow = A.shape[0]
    ratio = Nnz/(Nrow*Nrow)
    plt.title("Nearest neighbour connectivity")
    plt.xlabel("Number of non-zeros: " + str(Nnz) + " (%.3f %%)" %(ratio*100))
    plt.savefig(filename) 
Example 3
Project: bipartiteSBM   Author: junipertcy   File: painter.py    GNU General Public License v3.0 5 votes vote down vote up
def paint_sorted_adj_mat(mb, edgelist, output=None, figsize=(10, 10), dpi=300, invert=True):
    font = {'family': 'serif'}
    plt.figure(figsize=(10, 10))
    fig, ax = plt.subplots()
    mb = np.argsort(mb)
    A = np.zeros([len(mb), len(mb)])
    for edge in edgelist:
        e0 = int(edge[0])
        e1 = int(edge[1])
        A[np.argwhere(mb == e0)[0][0]][np.argwhere(mb == e1)[0][0]] += 1
        A[np.argwhere(mb == e1)[0][0]][np.argwhere(mb == e0)[0][0]] += 1
    M = sps.csr_matrix(A)
    plt.spy(M, markersize=0.01, marker=",")
    plt.xlabel(f"(Node index $i$) / {len(mb)}", fontdict=font)
    plt.ylabel(f"(Node index $i$) / {len(mb)}", fontdict=font)

    plt.xticks(np.linspace(0, 1, 5) * len(mb), ('0', '0.25', '0.5', '0.75', '1'))
    plt.yticks(np.linspace(0, 1, 5) * len(mb), ('0', '0.25', '0.5', '0.75', '1'))
    if invert:
        plt.gca().invert_yaxis()
        ax.tick_params(axis="y", direction="in")
        ax.tick_params(axis="x", direction="in")
        ax.xaxis.set_ticks_position("bottom")
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
    if output is not None:
        plt.savefig(output, dpi=dpi, transparent=True) 
Example 4
Project: elastic_benchmarks   Author: ManuelMBaumann   File: marmousi2.py    MIT License 5 votes vote down vote up
def makespyplot( matrix, name, imgtype=None ):
  if not scipy.sparse.isspmatrix( matrix ):
      matrix = matrix.toscipy()

  with plot.PyPlot( name, ndigits=0, imgtype=imgtype ) as plt:
    plt.spy( matrix, markersize=0.8, color='black')
    plt.title( name+', nnz = '+str(matrix.nnz) ) 
Example 5
Project: elastic_benchmarks   Author: ManuelMBaumann   File: elast_wedge.py    MIT License 5 votes vote down vote up
def makespyplot( matrix, name, imgtype=None ):
  if not scipy.sparse.isspmatrix( matrix ):
      matrix = matrix.toscipy()
  with plot.PyPlot( name, ndigits=0, imgtype=imgtype ) as plt:
    plt.spy( matrix, markersize=0.8, color='black')
    plt.title( name+', nnz = '+str(matrix.nnz) ) 
Example 6
Project: florence   Author: romeric   File: LinearSolver.py    MIT License 5 votes vote down vote up
def SparsityPattern(self,A):
        import matplotlib.pyplot as plt
        plt.spy(A)
        plt.grid('on')
        plt.show() 
Example 7
Project: PySMRS   Author: DavideNardone   File: SMRS.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def plot_sparsness(self):
        plt.spy(self.C, markersize=1, precision=0.01)
        plt.show() 
Example 8
Project: PySMRS   Author: DavideNardone   File: demo_video.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def plot_sparsness(C):

    plt.spy(C)
    plt.show() 
Example 9
Project: DiCoNet   Author: alexnowakvila   File: Logger.py    MIT License 5 votes vote down vote up
def plot_Phis_sparsity(self, Phis, fig=0):
        Phis = [phis[0].data.cpu().numpy() for phis in Phis]
        plt.figure(fig)
        plt.clf()
        for i, phi in enumerate(Phis):
            plt.subplot(1, len(Phis), i + 1)
            # plot first element of the batch
            plt.spy(phi, precision=0.001, marker='o', markersize=2)
            plt.xticks([])
            plt.yticks([])
            plt.title('k={}'.format(i))
        path = os.path.join(self.path, 'Phis.png')
        plt.savefig(path) 
Example 10
Project: csnmf   Author: marianotepper   File: test_tsqr.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_tsqr(create_func):
    mat, data = create_func()
    n = mat.shape[1]

    q, r = csnmf.tsqr.qr(data)

    dot_graph(q.dask, filename='q')
    dot_graph(r.dask, filename='r')

    print q.shape
    q = np.array(q)

    r = np.array(r)
    print r.shape

    print np.linalg.norm(mat - np.dot(q, r))

    assert np.allclose(mat, np.dot(q, r))
    assert np.allclose(np.eye(n, n), np.dot(q.T, q))
    assert np.all(r == np.triu(r))

    plt.figure()
    plt.subplot(2, 4, 1)
    plt.imshow(mat, interpolation='nearest')
    plt.title('Original matrix')
    plt.subplot(2, 4, 2)
    plt.imshow(q, interpolation='nearest')
    plt.title('$\mathbf{Q}$')
    plt.subplot(2, 4, 3)
    plt.imshow(np.dot(q.T, q), interpolation='nearest')
    plt.title('$\mathbf{Q}^T \mathbf{Q}$')
    plt.subplot(2, 4, 4)
    plt.imshow(r, interpolation='nearest')
    plt.title('$\mathbf{R}$')

    plt.subplot(2, 4, 8)
    plt.spy(r)
    plt.title('Nonzeros in $\mathbf{R}$') 
Example 11
Project: tools   Author: Olsthoorn   File: checker.py    GNU General Public License v3.0 5 votes vote down vote up
def spy(self, A, name=None):
        '''spy nan values in array A'''
        if not isinstance(A, np.ndarray):
            if name is None:
                name = 'Input'
            raise Exception("{} must b an array".format(name))

        if not np.any(np.isnan(A)):
            if name is None:
                name = 'array'
            print('There are no NaNs in {}'.format(name))
        else:
            if name is None:
                name = 'list'

            if A.ndim == 2: # make it 3D to loop over layers
                A = A[np.newaxis, :, :]

            layers = A.shape[0]
            fig, ax = plt.subplots(layers, 1)
            ax.set_title('Nans in {}'.format(name))
            if not isinstance(ax, list):
                ax = [ax]
            for iL in layers:
                ax[iL].set_title('spy layer 1 for nans')
                ax[iL].set_xlabel('x [m]')
                ax[iL].set_ylabel('y [m]')
                plt.spy(A[iL], ax=ax[iL]) 
Example 12
Project: csci5622_titantic_ml   Author: prheenan   File: analysis.py    GNU General Public License v2.0 5 votes vote down vote up
def plotFeatMatr(toPlot,featureObjects,featureMat,saveDir,label,badIdx):
    nFeats = featureMat.shape[1]
    nnzPerFeature = toPlot.getnnz(0)
    # get the indices to sort this ish.
    # how many should we use?...
    # get the top N most common
    mostCommon = np.argsort(nnzPerFeature)[-nFeats//7:]
    # get their labels
    featLabels = [f.label() for f in featureObjects]
    # get a version imshow can handle
    matImage = toPlot.todense()
    # fix the aspect ratio
    aspectSkew = len(badIdx)/nFeats
    aspectStr = 1./aspectSkew
    # plot everything
    ax = plt.subplot(1,1,1)
    cax = plt.imshow(matImage,cmap=plt.cm.hot_r,aspect=aspectStr,
                     interpolation="nearest")
    plt.spy(toPlot,marker='s',markersize=1.0,color='b',
            aspect=aspectStr,precision='present')
    cbar = plt.colorbar(cax, ticks=[0, 1], orientation='vertical')
    # horizontal colorbar
    cbar.ax.set_yticklabels(['Min Feat', 'Max Feat'],
                            fontsize=g_label)
    ax.set_xticks(range(nFeats))
    ax.set_xticklabels(featLabels,rotation='vertical')
    plt.xlabel("Feature Number",fontsize=g_label)
    plt.ylabel("Individual",fontsize=g_label)
    return aspectStr