如何在plotly.dash中显示网络图的结果

发布于 2025-02-07 08:36:20 字数 2357 浏览 3 评论 0原文

我有一个图形的几个节点之间的边缘列表,例如.csv文件。我正在读取提到的文件并将其存储在dash store组件下:

dataset = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
del dataset[dataset.columns[0]]
return  html.Div(className="mx-auto text-center", children=[
dcc.Store(id="approach-1-dataset",  data=dataset.to_dict('records'))]

然后使用networkx在用户单击视图中的按钮之后,创建图形,如下:

@app.callback(Output('visualization-container', 'children'),
          Input('visualize-button', 'n_clicks'),
          State('dataset', 'data'))
def visualize_graph(n1,dataset):
    if n1:
        main_dataset = pd.DataFrame.from_dict(dataset)
        pd.set_option('precision',10)
        G = nx.from_pandas_edgelist(main_dataset, 'member1', 'member2', create_using = nx.Graph())
        nodes = G.nodes()
        degree = G.degree()
        colors = [degree[n] for n in nodes]
        size = [(degree[n]) for n in nodes]
        pos = nx.kamada_kawai_layout(G)
        pos = nx.spring_layout(G, k = 0.2)
        cmap = plt.cm.viridis_r
        cmap = plt.cm.Greys
        fig = plt.figure(figsize = (15,9), dpi=100)
        nx.draw(G,pos,alpha = 0.8, nodelist = nodes, node_color = colors, node_size = size , with_labels= False,font_size = 6, width = 0.2, cmap = cmap, edge_color ='yellow')
        fig.set_facecolor('#0B243B')
        return dcc.Graph(figure = fig)
    return ""

使用此代码,我在视图中会收到以下错误:

回调错误更新可视化container.children

dash.exceptions.invalidcallbackreturnvalue:< output可视化container.children.children >返回具有类型的值的回调 Graph不可序列化。所讨论的价值是 要么返回的唯一值,要么在返回的最高级别 列表,并且具有字符串表示图形(图=<图大小1500x900,带有1个轴>)一般而言,dash属性只能是dash 组件,字符串,字典,数字,无或列表。

以及我的控制台中的错误:

断言失败:( nsviewSurryseBuildingLayerTreeFordisPlay()!=当前buildinglayertree),函数nsviewSetcurrance buildinglayertreefordisplay,file nsview.m,第13477行。

值得一提的是,当我在我运行的情况下,当我在jup in It It It It It It It In In jup y时,值得一提在dash调用中,并将结果返回为dcc.graph组件,我会得到错误。

我该如何解决这个问题?

我的.csv文件如下:

Member1,Member2,重量

200114206,3949436,1

217350178,8539046,1

193986670,8539046,2

I have a list of edges between several nodes of a graph as a .csv file. I am reading the mentioned file and storing it in a Dash Store component like below:

dataset = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
del dataset[dataset.columns[0]]
return  html.Div(className="mx-auto text-center", children=[
dcc.Store(id="approach-1-dataset",  data=dataset.to_dict('records'))]

Then using NetworkX the graph is created after the user clicks on a button in the view like below:

@app.callback(Output('visualization-container', 'children'),
          Input('visualize-button', 'n_clicks'),
          State('dataset', 'data'))
def visualize_graph(n1,dataset):
    if n1:
        main_dataset = pd.DataFrame.from_dict(dataset)
        pd.set_option('precision',10)
        G = nx.from_pandas_edgelist(main_dataset, 'member1', 'member2', create_using = nx.Graph())
        nodes = G.nodes()
        degree = G.degree()
        colors = [degree[n] for n in nodes]
        size = [(degree[n]) for n in nodes]
        pos = nx.kamada_kawai_layout(G)
        pos = nx.spring_layout(G, k = 0.2)
        cmap = plt.cm.viridis_r
        cmap = plt.cm.Greys
        fig = plt.figure(figsize = (15,9), dpi=100)
        nx.draw(G,pos,alpha = 0.8, nodelist = nodes, node_color = colors, node_size = size , with_labels= False,font_size = 6, width = 0.2, cmap = cmap, edge_color ='yellow')
        fig.set_facecolor('#0B243B')
        return dcc.Graph(figure = fig)
    return ""

Using this code I get the following error in my view:

Callback error updating visualization-container.children

dash.exceptions.InvalidCallbackReturnValue: The callback for <Outputvisualization-container.children> returned a value having type
Graph which is not JSON serializable. The value in question is
either the only value returned, or is in the top level of the returned
list, and has string representation Graph(figure=<Figure size 1500x900 with 1 Axes>) In general, Dash properties can only be dash
components, strings, dictionaries, numbers, None, or lists of those.

And this error in my console:

Assertion failed: (NSViewIsCurrentlyBuildingLayerTreeForDisplay() != currentlyBuildingLayerTree), function NSViewSetCurrentlyBuildingLayerTreeForDisplay, file NSView.m, line 13477.

It is worth mentioning that the same code works pretty fine when I run it directly in a Jupyter notebook but when I try to run it in a dash call back and return the result as a dcc.Graph component I get the errors.

How can I solve this issue?

My .csv file looks like below:

member1,member2,weight

200114206,3949436,1

217350178,8539046,1

.

.

.

193986670,8539046,2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝梦月影 2025-02-14 08:36:20

您可以将图形转换为基本64编码的对象,您可以在仪表板中显示为HTML图像。尝试下面的摘要以获取工作示例。

但是,如果您想与网络图中的“图”一起使用,请不要使用dcc.graph,而要使用cyto.cytoscape。参见 https://dash.plotly.com/cytoscape

import dash
from dash import html, dcc
from dash.dependencies import Output, Input

import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
import io
import base64

dataset = [
    (200114206,3949436,1),
    (217350178,8539046,1)
]

main_dataset = pd.DataFrame(dataset, columns=["member1" ,"member2", "weight"])
G = nx.from_pandas_edgelist(main_dataset, 'member1', 'member2', create_using = nx.Graph())
nodes = G.nodes()
degree = G.degree()
colors = [degree[n] for n in nodes]
size = [(degree[n]) for n in nodes]
pos = nx.spring_layout(G, k = 0.2)
cmap = plt.cm.Greys
fig = plt.figure(figsize=(15,9), dpi=100)
nx.draw(G, pos, alpha=0.8, nodelist=nodes, node_color=colors, node_size=size, with_labels=False, font_size=6, width=0.2, cmap=cmap, edge_color ='yellow')
fig.set_facecolor('#0B243B')

buffer = io.BytesIO()
plt.savefig(buffer, format="jpg")
buffer.seek(0)
base64_encoded_image = base64.b64encode(buffer.read()).decode('utf-8')

app = dash.Dash(__name__)
server = app.server
app.config.suppress_callback_exceptions = True

app.layout = html.Div(children=[
    html.Button(id="visualisation_button", children="click me"),
    html.Div(id="visualisation_block")
    ]
)

@app.callback(
    Output("visualisation_block", "children")
    ,Input("visualisation_button", "n_clicks"))
def update_vis(n_clicks):
    if n_clicks:

        base64_encoded_image
        return html.Img(id=f'nxplot_img',
                 src=f'data:image/png;base64, {base64_encoded_image}',
                 style = {'height': '50%', 'width': "50%"}
                 )

app.run_server()

You can convert the figure to a base64-encoded object, which you can display as an html-image in dash. Try the snippet below for a working example.

But if you want to work with a 'graph' as in network-graph, don't use Dcc.Graph, but use cyto.Cytoscape. See https://dash.plotly.com/cytoscape

import dash
from dash import html, dcc
from dash.dependencies import Output, Input

import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
import io
import base64

dataset = [
    (200114206,3949436,1),
    (217350178,8539046,1)
]

main_dataset = pd.DataFrame(dataset, columns=["member1" ,"member2", "weight"])
G = nx.from_pandas_edgelist(main_dataset, 'member1', 'member2', create_using = nx.Graph())
nodes = G.nodes()
degree = G.degree()
colors = [degree[n] for n in nodes]
size = [(degree[n]) for n in nodes]
pos = nx.spring_layout(G, k = 0.2)
cmap = plt.cm.Greys
fig = plt.figure(figsize=(15,9), dpi=100)
nx.draw(G, pos, alpha=0.8, nodelist=nodes, node_color=colors, node_size=size, with_labels=False, font_size=6, width=0.2, cmap=cmap, edge_color ='yellow')
fig.set_facecolor('#0B243B')

buffer = io.BytesIO()
plt.savefig(buffer, format="jpg")
buffer.seek(0)
base64_encoded_image = base64.b64encode(buffer.read()).decode('utf-8')

app = dash.Dash(__name__)
server = app.server
app.config.suppress_callback_exceptions = True

app.layout = html.Div(children=[
    html.Button(id="visualisation_button", children="click me"),
    html.Div(id="visualisation_block")
    ]
)

@app.callback(
    Output("visualisation_block", "children")
    ,Input("visualisation_button", "n_clicks"))
def update_vis(n_clicks):
    if n_clicks:

        base64_encoded_image
        return html.Img(id=f'nxplot_img',
                 src=f'data:image/png;base64, {base64_encoded_image}',
                 style = {'height': '50%', 'width': "50%"}
                 )

app.run_server()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文