【问题标题】:How to plot a subset of nodes of a networkx graph如何绘制networkx图的节点子集
【发布时间】:2020-07-30 08:35:30
【问题描述】:

这是与我的代码相似的代码

import networkx as nx
from matplotlib import pyplot as plt
%matplotlib notebook
import pandas as pd

data={"A":["T1","T2","tom","adi","matan","tali","pimpunzu","jack","arzu"],
      "B":["end","end","T1","T1","T1","T2","T2","matan","matan"]}

df=pd.DataFrame.from_dict(data)

G = nx.from_pandas_edgelist(df,source='A',target='B', edge_attr=None, create_using=nx.DiGraph())
f, ax = plt.subplots(figsize=(10, 10))
nx.draw(G, with_labels=True, font_weight='bold', ax=ax)

例如,我喜欢绘制图表的一部分,我喜欢只绘制["T1","matan","jack","arzu"]

这就是我想要得到的

data={"A":["jack","arzu","matan"],
      "B":["matan","matan","T1"]}

df=pd.DataFrame.from_dict(data)

G = nx.from_pandas_edgelist(df,source='A',target='B', edge_attr=None, create_using=nx.DiGraph())
f, ax = plt.subplots(figsize=(10, 10))
nx.draw(G, with_labels=True, font_weight='bold', ax=ax)

我可以列出我喜欢绘制的内容吗? 或者我可以写出我喜欢在它们之间绘制的节点吗?

【问题讨论】:

    标签: python pandas matplotlib plot networkx


    【解决方案1】:

    您可以从节点列表中生成nx.subgraph,然后像上面那样进行绘制:

    H = nx.subgraph(G, ["T1","matan","jack","arzu"])
    nx.draw(H, with_labels=True, font_weight='bold', node_color='lightblue', node_size=500)
    

    【讨论】:

      【解决方案2】:

      您正在尝试绘制原始图的子图。为此,您可以使用networkx.Graph.subgraph 方法:

      import networkx as nx
      import pandas as pd
      
      # Build a graph using a pd.DataFrame
      data = {"A": ["T1","T2","tom","adi","matan","tali","pimpunzu","jack","arzu"],
              "B": ["end","end","T1","T1","T1","T2","T2","matan","matan"]}
      df = pd.DataFrame.from_dict(data)
      G = nx.from_pandas_edgelist(df, source='A', target='B', edge_attr=None,
                                  create_using=nx.DiGraph())
      
      # Build subgraph containing a subset of the nodes, and edges between those nodes
      subgraph = G.subgraph(["T1","matan","jack","arzu"])
      

      现在您只需要使用您已经使用过的 matplotlib 中的相同函数来简单地绘制新图形。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-28
        • 1970-01-01
        • 1970-01-01
        • 2021-01-26
        • 2019-10-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多