首页 > 解决方案 > Plotly:嵌入散点图/网络图标记的条形图

问题描述

我正在尝试可视化贝叶斯网络,并希望叠加一个简单的条形图,显示边际概率分布而不是标记/节点。

例如

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import networkx as nx

G = nx.DiGraph([
    ('Rain', 'Grass_Wet'),
    ('Sprinkler', 'Grass_Wet'),
    ('Rain', 'Sprinkler')])

app = dash.Dash(__name__)

def generate_network_graph(G):        
    pos = nx.drawing.layout.spectral_layout(G)
    # Add additional attribute specifying node position
    label_col = 'label'
    for node in G.nodes:
        G.nodes[node]['pos'] = list(pos[node])
        G.nodes[node][label_col] = node
    # Define Figure
    traceRecode = []  # contains edge_trace, node_trace, middle_node_trace

    index = 0
    for edge in G.edges:
        x0, y0 = G.nodes[edge[0]]['pos']
        x1, y1 = G.nodes[edge[1]]['pos']
        #weight = float(G.edges[edge]['TransactionAmt']) / max(edge1['TransactionAmt']) * 10
        trace = go.Scatter(x=tuple([x0, x1, None]), y=tuple([y0, y1, None]),
                           mode='lines')
        traceRecode.append(trace)
        index = index + 1

    node_trace = go.Scatter(x=[], y=[], hovertext=[], text=[], mode='markers+text', textposition="bottom center", marker={'size': 20})

    index = 0
    for node in G.nodes():
        x, y = G.nodes[node]['pos']
        node_trace['x'] += tuple([x])
        node_trace['y'] += tuple([y])
        index = index + 1

    traceRecode.append(node_trace)

    figure = {
        "data": traceRecode,
        "layout": go.Layout(title='Bayesian Network', showlegend=False, hovermode='closest',
                            margin={'b': 40, 'l': 40, 'r': 40, 't': 40},
                            xaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
                            yaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
                            height=600

                            )}
    return figure

def create_bar_plot():
    figure = go.Figure(go.Bar(
            x=[0.6, 0.4],
            y=['Yes', 'No'],
            orientation='h'))

    return figure


app.layout = html.Div(
    [
        html.Div(
            # className="six columns",
            children=[dcc.Graph(id="my-graph", figure=generate_network_graph(G))],
        ),
        html.Div(children=[dcc.Graph(id="my-graph2", figure=create_bar_plot())]),
    ]
)

if __name__ == '__main__':
    app.run_server()

将生成第一个输出。

现在

但是我需要在每个节点上嵌入或重叠条形图,以显示该节点的边际概率分布。我希望能够从 networkx 获取网络方向,因为它对我的应用程序非常重要。网络非常大,不可能直接先验地指定条形图位置。

期望输出

标签: pythonmatplotlibnetworkinggraphplotly-dash

解决方案


没有在 python 中创建节点嵌入条形图的功能(替代方法 - manual.cytoscape.org/en/stable/Styles.html 请参阅教程 6:节点图表) - 但是可以使用 dash-cytoscape 作为创建饼图如下图

将以下块添加到 Cytoscape 默认破折号样式表将创建具有以下样式的节点

default_stylesheet = [{
    "selector": "node",
    "style": {
        "background-color": "green",
        "pie-size": "80%",
        "pie-1-background-color": "#E8747C",
        "pie-1-background-size": f"mapData(Yes, 0, 1, 0, 100)",
        "pie-2-background-color": "#74CBE8",
        "pie-2-background-size": f"mapData(No, 0, 1, 0, 100)",
    }]

在此处输入图像描述

Dash-cytoscape 允许链接中给出的所有大多数 cytoscape js 样式选项,这可能足以满足您的特定用例

有用的链接:

https://js.cytoscape.org/demos/pie-style/ https://dash.plot.ly/cytoscape


推荐阅读