簡體   English   中英

Matplotlib抱怨networkx鄰接矩陣的形狀

[英]Matplotlib complains about shape of networkx adjacency matrix

以下代碼導致在figaspectfigaspect我的矩陣的形狀時figaspect ,但是該形狀似乎是正確的(4 x 4 2D數組)。 我在做蠢事嗎?

import networkx as nx
import matplotlib.pyplot as plt
g = nx.Graph()
g.add_edge(1, 2)
g.add_edge(2, 3)
g.add_edge(3, 4)
matrix = nx.to_scipy_sparse_matrix(g)
print(matrix.shape)
plt.matshow(matrix)
plt.show()

錯誤:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-118-70cfbe8cdb62> in <module>
      7 matrix = nx.to_scipy_sparse_matrix(g)
      8 print(matrix.shape)
----> 9 plt.matshow(matrix)
     10 plt.show()

/usr/local/lib/python3.7/site-packages/matplotlib/pyplot.py in matshow(A, fignum, **kwargs)
   2180         # Extract actual aspect ratio of array and make appropriately sized
   2181         # figure.
-> 2182         fig = figure(fignum, figsize=figaspect(A))
   2183         ax = fig.add_axes([0.15, 0.09, 0.775, 0.775])
   2184     im = ax.matshow(A, **kwargs)

/usr/local/lib/python3.7/site-packages/matplotlib/figure.py in figaspect(arg)
   2740     # Extract the aspect ratio of the array
   2741     if isarray:
-> 2742         nr, nc = arg.shape[:2]
   2743         arr_ratio = nr / nc
   2744     else:

ValueError: not enough values to unpack (expected 2, got 0)

但打印的形狀是(4,4)

嘗試使用todense

plt.matshow(matrix.todense())

哪里,

print(matrix)

輸出:

  (0, 1)    1
  (1, 0)    1
  (1, 2)    1
  (2, 1)    1
  (2, 3)    1
  (3, 2)    1

和,

print(matrix.todense())

輸出:

[[0 1 0 0]
 [1 0 1 0]
 [0 1 0 1]
 [0 0 1 0]]

Plottting:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM