【问题标题】:subplots with network analysis networkx带有网络分析 networkx 的子图
【发布时间】:2014-02-20 00:54:20
【问题描述】:

我一直在研究其他 networkx 绘图帖子,但我很难让它们适应我的问题。

1) 如何在没有预定义对象数量的情况下创建带有网络图的子图?该函数会动态抓取它。

2) 例如,是否有一种简单的方法可以通过仅限制权重超过 2 的边来过滤网络图?还是我必须编辑网络对象本身才能这样做?

更新 #2:我想出了一种按程度过滤的方法(见下文)。 我想知道是否有更好的方法让我的网络数据更易于理解?

nol 的格式为 [ [Year, networkobject], [Year, networkobject]]

def standardgraph_multiyear(nol, minimumdegree):
"""
Plots multiple graphs based on year
nol = takes in a LIST of [year, network object]
minimum = takes in a digit to filter nodes by degree
"""

#Each iteration prints a new subplot 
numrows = len(nol)
fig = plt.figure(figsize=(10,60))    
for i, val in enumerate(nol):
    gloc = numrows,1,i+1
    plt.subplot(numrows, 1, i+1)

    if minimumdegree > 0:
        outdeg = val[1].degree()
        to_keep = [n for n in outdeg if outdeg[n] > minimumdegree]
        mingraph = val[1].subgraph(to_keep)
        pos = nx.spring_layout(mingraph, iterations=200)
        nx.draw(mingraph, pos, font_size=8, with_labels=True)
        nx.draw_networkx_edges(mingraph, pos, alpha=.2)
        nx.draw_networkx_nodes(mingraph, pos, node_size=60, font_size =8, labels=True)
        nx.draw_networkx_labels(mingraph, pos, font_color='k', font_size=8)
        plt.title("Year {0}".format(val[0]), loc = 'center', fontsize=20)

    if minimumdegree == 0:
        outdeg = val[1].degree()
        to_keep = [n for n in outdeg if outdeg[n] > minimumdegree]
        mingraph = val[1].subgraph(to_keep)
        pos = nx.spring_layout(mingraph, iterations=200)
        nx.draw(mingraph, pos, font_size=8, with_labels=True)
        nx.draw_networkx_edges(mingraph, pos, alpha=.2)
        nx.draw_networkx_nodes(mingraph, pos, node_size=60, font_size =8, labels=True)
        nx.draw_networkx_labels(mingraph, pos, font_color='k', font_size=8)
        plt.title("Year {0}".format(val[0]), loc = 'center', fontsize=20)
return 

fig.savefig('out.png', dpi=100)

【问题讨论】:

    标签: python networking matplotlib networkx


    【解决方案1】:

    您的超出范围错误可能来自对plt.subplot(221+i) 的调用,因为您似乎没有将 i 限制为

    (您似乎也有一些相互冲突的代码来组装绘图:调用 plt.subplots(1,1) 和稍后请求 2x2 网格)。

    different question 中,我使用了更基本的plt.subplot(xxx) 语法来生成多个子图(遵循来自networkx 的four grids example)。但您也可以如下所示执行此操作,将 ax= 关键字参数设置为已经存在的一组轴。请注意在渲染到每个轴之前对sca() 的调用,我需要这样做才能使其工作。

    我还展示了一种过滤边的方法,如下所示,它不需要修改底层图形:相反,您可以根据图形中的数据构造所需的边线宽,并将其用作draw_networkx_edges 的参数。

    编辑(重新更新问题):示例代码现在包含更明确的说明,说明如何处理未知数量的网络。

    import matplotlib.pyplot as plt
    import networkx as nx
    import numpy as np
    
    n = 15; m = 40                        # graph size
    L = np.random.choice(xrange(n), 2*m)  # select some edge destinations
    weights = 0.5 + 5 * np.random.rand(m) # give each edge a weight
    
    
    G = nx.Graph()                           # create a graph object
    G.add_nodes_from(xrange(n))              # add n nodes to it
    for i, (fr, to) in enumerate(zip(L[1::2], L[::2])): 
      G.add_edge(fr, to, weight=weights[i])  # add each edge
    
    # use one of the edge properties to control line thickness
    edgewidth = [ d['weight'] for (u,v,d) in G.edges(data=True)]
    
    # and create a filtered version (still need an entry for each edge)
    w_threshold = 2
    edgewidth_filtered = [ d['weight'] if d['weight'] > w_threshold else 0
                          for (u,v,d) in G.edges(data=True)]
    
    # alt. filtering - all edges that meet some criterion are displayed uniformly 
    binary_filtered_edges = [ 1 if d['weight'] > w_threshold else 0
                          for (u,v,d) in G.edges(data=True)]
    
    titles = [ 'edges drawn with lineweight=1', 'edge width from edge weight',
      'edge width from edge weight, only strong edges',
      'strong edges shown as lineweight=1', ]
    
    edge_display_params = [ np.ones(len(edgewidth),), edgewidth,  
      edgewidth_filtered, binary_filtered_edges,]
    
    # to illustrate drawing an unknown number of graphs, add some repeats repeats
    n_extra = np.random.randint(0, 5)
    indices = range(len(edge_display_params)) * 3
    indices = indices[len(edge_display_params) + n_extra:]
    
    # layout
    pos = nx.spring_layout(G, iterations=50)
    pos = nx.circular_layout(G)
    #pos = nx.random_layout(G)
    
    # rendering
    fig = plt.figure(1); plt.clf()
    # compute a grid size that will fit all graphs on it (couple blanks likely)
    nr = int(np.ceil(np.sqrt(len(indices))))
    fig, ax = plt.subplots(nr, nr, num=1)
    
    for i, j in enumerate(indices):
        # dereference index into valid data (needed here since some repeated rather
        # than creating more, to illustrate handling unknown amount of data)
        k = indices[j]
        widths = edge_display_params[k]
        # compute index for the subplot, and set this subplot as current
        ix = np.unravel_index(i, ax.shape)
        plt.sca(ax[ix])
        # draw all nodes homogeneously, and edge weights as filtered
        nx.draw_networkx_nodes(G, pos, ax=ax[ix])
        nx.draw_networkx_edges(G, pos, width=widths, ax=ax[ix],)
    
        ax[ix].set_title(titles[k], fontsize=10)
        ax[ix].set_axis_off()
    
    plt.show()
    

    此示例四次使用相同的输入图,但显然您可以将单个过滤器应用于不同的图(通过在绘图循环中进行过滤)而不是应用不同的过滤器。


    下面显示了一个创建额外 4 个图表的运行,因此我们有一个未使用的窗格:

    【讨论】:

    • 您指的是plt.subplots(2,2, num=1) 调用中的值吗? subplots 是创建多个轴句柄的便捷函数。前两个参数是#rows、#cols,num=1 只是为了让它使用数字 1(在交互式会话中很有用,因此您不会创建很多数字)。使用nr=int(np.ceil(np.sqrt(len(graph_list))); fig, ax = plt.subplots(nr, nr, num=1) 创建一个足够大的方形网格来绘制graph_list 中的每个图表怎么样?
    • 嗯,当我这样做时,我得到了一个巨大的网格,但所有的情节都只是进入一个角落。我对此有所了解: plt.subplot(numrows, 1, i+1) 其中 i 只是网络对象的索引,numrows 是每年网络对象的数量。然而,每个子情节都被压扁了。我尝试添加一个 figsize 关键字参数,但它给了我一个语法错误。感谢您的帮助!
    • figsize 参数用于plt.figure(),可以通过plt.subplots 作为关键字arg 传递,但不能通过plt.subplot 传递。我上面的建议使用ax 的形状来适当地遍历索引,但请注意循环内的索引是ix 而不是i。如果这不能解决它,您可以编辑您的原始问题并添加更多详细信息/更新,因为评论框并不是真正解决大问题的地方..
    • 嗨,我已经解决了 figsize 问题,但现在我正在尝试实施您的边缘过滤技术。我只是想实现选项 3 (edgewidth_filtered),但我认为我做得不对。提前致谢!
    • 我想,我发现了我原来的两个问题,但我意识到我真正的问题是如何最好地 c
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    相关资源
    最近更新 更多