When sparse matrices have explicit zero values, `axes.spy` plots those zero values. This behavior seems unintentional. For example, the following code should have a main diagonal with markers missing in the middle, but `spy` currently plots a full main diagonal.

## ···

#~~~~~~~~~~~

import scipy.sparse as sparse

import matplotlib.pyplot as plt

sp = sparse.spdiags([[1,1,1,0,0,0,1,1,1]], [0], 9, 9)

plt.spy(sp, marker='.')

#~~~~~~~~~~~

Below is a patch which only plots the nonzero entries in a sparse matrix. Note, sparse matrices with all zero entries raises an error; this behavior differs from dense matrices. I could change this behavior, but I wanted to minimize the code changed.

Cheers,

-Tony

PS: this patch also includes two trivial changes to some examples.

# Index: lib/matplotlib/axes.py

# --- lib/matplotlib/axes.py (revision 6122)

+++ lib/matplotlib/axes.py (working copy)

@@ -6723,9 +6723,11 @@

else:

if hasattr(Z, 'tocoo'):

c = Z.tocoo()

- y = c.row

- x = c.col

- z = c.data

+ nonzero = c.data != 0.

+ if all(nonzero == False):

+ raise ValueError('spy cannot plot sparse zeros matrix')

+ y = c.row[nonzero]

+ x = c.col[nonzero]

else:

Z = np.asarray(Z)

if precision is None: mask = Z!=0.

Index: examples/pylab_examples/masked_demo.py

--- examples/pylab_examples/masked_demo.py (revision 6122)

+++ examples/pylab_examples/masked_demo.py (working copy)

@@ -1,4 +1,4 @@

-#!/bin/env python

+#!/usr/bin/env python

'''

Plot lines with points masked out.

# Index: examples/misc/rec_groupby_demo.py

--- examples/misc/rec_groupby_demo.py (revision 6122)

+++ examples/misc/rec_groupby_demo.py (working copy)

@@ -2,7 +2,7 @@

import matplotlib.mlab as mlab

-r = mlab.csv2rec('data/aapl.csv')

+r = mlab.csv2rec('../data/aapl.csv')

r.sort()

def daily_return(prices):