我想創建一個網路,您可以將滑鼠懸停在每個標簽上以互動方式閱讀它。
我正在使用 jupyter 實驗室,規格是:選定的 Jupyter 核心包...
IPython : 7.6.1
ipykernel : 5.1.1
ipywidgets : 7.6.5
jupyter_client : 7.0.6
jupyter_core : 4.8.1
jupyter_server : not installed
jupyterlab : 1.0.2
nbclient : not installed
nbconvert : 5.5.0
nbformat : 4.4.0
notebook : 6.0.0
qtconsole : 4.5.1
traitlets : 4.3.2
當我在 jupyter notebook 中運行這段代碼時:
import matplotlib.pyplot as plt
import numpy as np
import mpld3
fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'))
N = 100
scatter = ax.scatter(np.random.normal(size=N),
np.random.normal(size=N),
c=np.random.random(size=N),
s=1000 * np.random.random(size=N),
alpha=0.3,
cmap=plt.cm.jet)
ax.grid(color='white', linestyle='solid')
ax.set_title("Scatter Plot (with tooltips!)", size=20)
labels = ['point {0}'.format(i 1) for i in range(N)]
tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels)
mpld3.plugins.connect(fig, tooltip)
mpld3.show()
我從
但我收到一個錯誤:
TypeError: Object of type int is not JSON serializable
并且網路不會在我可以與之互動的新視窗中打開(理想情況下,互動網路無論如何都會保留在 jupyter 中)。
我將物件型別更改為字串以查看發生了什么:
final_net['col_A'] = pd.to_numeric(final_net['col_A'])
final_net['col_B'] = pd.to_numeric(final_net['col_B'])
隨著輸出:
col_A int64
col_B int64
But the error remains the same. When I remove the last line, mpld3.show() , the error disappears, so I just get a static image as an output, with no error, but no interactivity either.
I uninstalled and re-installed with conda as per 
I'm wonder if someone could show me how to edit my code to make the interactive feature appear (ideally in a jupyter notebook, if not it's ok if it opens in a new window).
uj5u.com熱心網友回復:
問題似乎G.nodes()不是標簽串列。您可以通過將其轉換為串列 ( list(G.nodes()))來獲取節點編號或標簽。
更新版本可能如下所示:
import matplotlib.pyplot as plt
import networkx as nx
import pandas as pd
import numpy as np
import mpld3
final_net = pd.DataFrame({'col_A': [6840, 6640, 823, 57019],
'col_B': [7431, 5217, 7431, 57019]})
G = nx.from_pandas_edgelist(final_net, 'col_A', 'col_B', ['col_A', 'col_B'])
print(final_net['col_A'][0:10])
print(final_net['col_B'][0:10])
edge_labels = nx.get_edge_attributes(G, "Edge_label")
pos = nx.spring_layout(G)
fig, ax = plt.subplots(subplot_kw=dict(facecolor='#EEEEEE'))
scatter = nx.draw_networkx_nodes(G, pos, ax=ax)
nx.draw_networkx_edges(G, pos, ax=ax)
labels = list(G.nodes())
tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels)
mpld3.plugins.connect(fig, tooltip)
mpld3.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/335145.html
標籤:python matplotlib networkx mpld3 mplcursors
