1

I sum my sparse matrix mat7 along axis=0 then plot.

mat7 = np.zeros(shape=(5,4))
mat7[2] = 5
mat7[3,1:3] = 7
print mat7
>[[ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 5.  5.  5.  5.]
 [ 0.  7.  7.  0.]
 [ 0.  0.  0.  0.]]

ax0 = plt.subplot2grid((1, 1), (0, 0), rowspan=1, colspan=1)
ax0.plot(np.sum(mat7,0))
plt.show()

enter image description here

I want on each sum value to have the row index of where nonzero element comes from. From 4 points here, what to do to have label (2),(2,3),(2,3),(2) , respectively? as the first and fourth points come from only 2nd row, and the second and third point on the plot come from sum of nonzero elements at 2nd and 3rd rows.

Because it is not index from column but the row that the sum already collapses, is it the way to link back and make a label?

Community
  • 1
  • 1
Jan
  • 1,389
  • 4
  • 17
  • 43

1 Answers1

3

you can use

  • np.nonzero() to find the row numbers of the non-zero elements
  • mpl.Axes.annotate to add text to marker points. Im indebted to the following answer for this part: Label python data points on plot

Here's an example:

import numpy as np
import matplotlib.pyplot as plt

mat7 = np.zeros(shape=(5,4))
mat7[2] = 5
mat7[3,1:3] = 7
print(mat7)

x = list(range(mat7.shape[1]))
y = np.sum(mat7,0)
labels = [np.nonzero(col)[0].tolist() for col in mat7.T]

ax0 = plt.subplot2grid((1, 1), (0, 0), rowspan=1, colspan=1)
ax0.plot(x,y)

for x,y,label in zip(range(4), np.sum(mat7,0), labels):
    ax0.annotate('{}'.format(label), xy=(x,y), textcoords='data')

plt.show()
Rob Buckley
  • 708
  • 4
  • 16