绘制总和(矩阵,轴= 0)并用非零元素的行索引标记该绘图总和
问题描述:
我将我的稀疏矩阵mat7
与axis=0
相加然后绘制。绘制总和(矩阵,轴= 0)并用非零元素的行索引标记该绘图总和
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()
我想每个总和值有哪里非零元素来自行索引。从这里4点开始,分别有什么标签(2),(2,3),(2,3),(2)
?因为第一和第四点来自第二排,并且第二和第三点来自第二和第三排非零元素的总和。
因为它不是从列索引而是总和已经崩溃的行,它是如何链回来制作标签的?
答
可以使用
- np.nonzero()来查找非零元素
- mpl.Axes.annotate添加文本标记点的行号。林感谢如下回答此部分:Label python data points on plot
下面是一个例子:
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()