networkxbipartite

Can I draw a bipartite graph from every dataset?


I am trying to draw a bipartite graph for my data set, which is like below:

source  target  weight
reduce  energy  25
reduce  consumption 25
energy  pennsylvania    4
energy  natural 4
consumption balancing   4

the code That I am trying to plot the graph is as below:

C_2021 = nx.Graph()
C_2021.add_nodes_from(df_final_2014['source'], bipartite=0)
C_2021.add_nodes_from(df_final_2014['target'], bipartite=1)
edges = df_final_2014[['source', 'target','weight']].apply(tuple, axis=1)
C_2021.add_weighted_edges_from(edges)

But when I check with the below code whether it is bipartite or not, I get the "False" feedback.

nx.is_bipartite(C_2021)

Could you please advise what the issue is?

The previous issue is resolved, but when I want to plot the bipartite graph with the below steps, I do not get a proper result. If someone could help me, I will be appreciated it:

top_nodes_2021 = set(n for n,d in C_2021.nodes(data=True) if d['bipartite']==0)
top_nodes_2021

the output of the above is:

{'reduce'}

bottom_nodes_2021 = set(C_2021) - top_nodes_2021
bottom_nodes_2021

the output of the above is:

{'balancing', 'consumption', 'energy', 'natural', 'pennsylvania '}

then plot it by:

pos = nx.bipartite_layout(C_2021,top_nodes_2021)
plt.figure(figsize=[8,6])
# Pass that layout to nx.draw
nx.draw(C_2021,pos,node_color='#A0CBE2',edge_color='black',width=0.2,
     edge_cmap=plt.cm.Blues,with_labels=True)

and the result is:

enter image description here


Solution

  • It works for me using your code. nx.is_bipartite(C_2021) returns true. Check the example below:

    import sys
    if sys.version_info[0] < 3: 
        from StringIO import StringIO
    else:
        from io import StringIO
    
    import pandas as pd
    
    data = StringIO('''source;target;weight
    reduce;energy;25
    reduce;consumption;25
    energy;pennsylvania ;4
    energy;natural;4
    consumption;balancing;4
    ''')
    
    df_final_2014 = pd.read_csv(data, sep=";")
    
    C_2021 = nx.Graph()
    C_2021.add_nodes_from(df_final_2014['source'], bipartite=0)
    C_2021.add_nodes_from(df_final_2014['target'], bipartite=1)
    edges = df_final_2014[['source', 'target','weight']].apply(tuple, axis=1)
    C_2021.add_weighted_edges_from(edges)
    
    nx.is_bipartite(C_2021)
    

    Finally to draw them get the bipartite sets. The data you passed during the creation is false (i.g. bipartite=0 and bipartite=1).

    Use the following commands:

    from networkx.algorithms import bipartite
    top_nodes_2021, bottom_nodes_2021 = bipartite.sets(C_2021)
    pos = nx.bipartite_layout(C_2021, top_nodes_2021)
    
    plt.figure(figsize=[8,6])
    # Pass that layout to nx.draw
    nx.draw(C_2021,pos,node_color='#A0CBE2',edge_color='black',width=0.2,
         edge_cmap=plt.cm.Blues,with_labels=True)
    

    With the following result: enter image description here