如何使用Python将属性添加到最高度中心节点?

时间:2018-01-09 04:24:39

标签: python pandas networkx

我正在寻找一种方法来增加最高度中心节点的大小,以便我可以根据类别添加C1或C2等属性。我尝试过一种解决方案,但并不完美。我想减少数据帧转换和节点位置代码。

需要提问/帮助: 1.在得到我需要的df之前,数据帧转换需要15个步骤。有没有办法在单线上做到这一点?

  1. 为了找到标签的x,y,我使用了试错法。 -0.186和-0.341但节点标签仍然不在中心节点内。有没有更好的方法来查找节点的x,y值?
  2. 请参阅我的解决方案:

    data= {        '0': [1,0,0,0,0,1],
                   '1': [0,1,0,0,0,0],
                   '2': [0,0,1,0,1,0],
                   '3': [0,0,0,1,0,0],
           'Newspaper': ['G1','G2','G3','G4','G5','G6']
          }
    df_result=pd.DataFrame(data)
    
    df_C0=df_result[['newspaper','C0']][df_result['C0'] ==1] 
    df_C1=df_result[['newspaper','C1']][df_result['C1'] ==1]
    df_C2=df_result[['newspaper','C2']][df_result['C2'] ==1]
    df_C3=df_result[['newspaper','C3']][df_result['C3'] ==1]
    
    #selecting
    df_C0.C0= df_C0.C0.apply(lambda x: 'C0')
    df_C1.C1= df_C1.C1.apply(lambda x: 'C1') 
    df_C2.C2= df_C2.C2.apply(lambda x: 'C2') 
    df_C3.C3= df_C3.C3.apply(lambda x: 'C3')
    
    
    #changing
    col=['newspaper', 'C']
    df_C0.columns=col
    df_C1.columns=col
    df_C2.columns=col
    df_C3.columns=col
    
    frames = [df_C0, df_C1, df_C2,df_C3]
    result = pd.concat(frames)
    
    
    #Creating the Graph object
    G=nx.from_pandas_dataframe(result, 'newspaper', 'C')
    fig=plt.figure(figsize=(12, 10))
    ax = fig.add_subplot(111)
    
    pos = nx.spring_layout(G,k=.25)
    x0,y0=pos.get('C0')
    x1,y1=pos.get('C1')
    x2,y2=pos.get('C2')
    x3,y3=pos.get('C3')
    
    x0 +=-0.186
    y0 +=-0.341
    
    x1 +=-0.186
    y1 +=-0.341
    
    x2 +=-0.186
    y2 +=-0.341
    
    x3 +=-0.186
    y3 +=-0.341
    
    ax.text(x0,y0, 'C0',color='green', fontsize=15)
    ax.text(x1,y1, 'C1',color='green', fontsize=15)
    ax.text(x2,y2, 'C2',color='green', fontsize=15)
    ax.text(x3,y3, 'C3',color='green', fontsize=15)
    
    nx.draw_networkx(G, pos=pos, node_size=100, with_labels=False, alpha=0.5)
    plt.show()
    

0 个答案:

没有答案