1

I'm trying to draw some graphs from an adjacency matrix stored in a text file (and loaded with Numpy), using networkx version 2.6.3 and matplotlib version 3.4.3.

I have this code:

import networkx as nx
from prettytable import PrettyTable
import numpy as np
import matplotlib.pyplot as plt


def calculate_network_properties(file_path):
    # Read the adjacency matrix from the file
    adj_matrix = np.loadtxt(file_path)

    # Create a networkx graph from the adjacency matrix
    G = nx.from_numpy_matrix(adj_matrix)

    # Relabel nodes to start from 1 instead of 0
    mapping = {node: node + 1 for node in G.nodes()}
    G = nx.relabel_nodes(G, mapping)

    # Calculate network properties
    num_nodes = G.number_of_nodes()
    num_edges = G.number_of_edges()
    density = nx.density(G)
    diameter = nx.diameter(G)
    global_clustering_coefficient = nx.average_clustering(G)
    local_clustering_coefficients = nx.clustering(G)
    avg_local_clustering_coefficient = sum(local_clustering_coefficients.values()) / len(local_clustering_coefficients)
    mean_shortest_path = nx.average_shortest_path_length(G)
    assortativity = nx.degree_assortativity_coefficient(G)
    communities = nx.algorithms.community.modularity_max.greedy_modularity_communities(G)
    modularity = nx.algorithms.community.modularity(G, communities)
    num_communities = len(communities)

    # Calculate centrality measures
    degree_centrality = nx.degree_centrality(G)
    closeness_centrality = nx.closeness_centrality(G)
    betweenness_centrality = nx.betweenness_centrality(G)
    eigenvector_centrality = nx.eigenvector_centrality(G)

    # Check if the network is small-world
    small_world = nx.algorithms.smallworld.sigma(G)

    # Create a table with the results
    table = PrettyTable()
    table.field_names = ['Characteristic', 'Result']
    table.add_row(['Number of nodes', num_nodes])
    table.add_row(['Number of edges', num_edges])
    table.add_row(['Graph density', density])
    table.add_row(['Graph diameter', diameter])
    table.add_row(['Global clustering coefficient', global_clustering_coefficient])
    table.add_row(['Average of local clustering coefficients', avg_local_clustering_coefficient])
    table.add_row(['Mean shortest path', mean_shortest_path])
    table.add_row(['Assortativity (r coefficient)', assortativity])
    table.add_row(['Modularity (Q coefficient)', modularity])

    table.add_row(['Number of communities found', num_communities])
    table.add_row(['Small-world sigma', small_world])

    print(table)

    # Create tables for centrality measures
    degree_table = PrettyTable()
    degree_table.field_names = ['Node', 'Degree Centrality']
    for node, centrality in degree_centrality.items():
        degree_table.add_row([node, centrality])
    print('Degree Centrality')
    print(degree_table)

    closeness_table = PrettyTable()
    closeness_table.field_names = ['Node', 'Closeness Centrality']
    for node, centrality in closeness_centrality.items():
        closeness_table.add_row([node, centrality])
    print('Closeness Centrality')
    print(closeness_table)

    betweenness_table = PrettyTable()
    betweenness_table.field_names = ['Node', 'Betweenness Centrality']
    for node, centrality in betweenness_centrality.items():
        betweenness_table.add_row([node, centrality])

    print('Betweenness Centrality')
    print(betweenness_table)

    eigenvector_table = PrettyTable()
    eigenvector_table.field_names = ['Node', 'Eigenvector Centrality']
    for node, centrality in eigenvector_centrality.items():
        eigenvector_table.add_row([node, centrality])
    print('Eigenvector Centrality')
    print(eigenvector_table)

    # Set node size based on degree centrality
    node_size = [v * 1000 for v in degree_centrality.values()]

    # Draw the graph for degree centrality
    fig, ax = plt.subplots()
    nx.draw(G, pos=nx.kamada_kawai_layout(G), node_size=node_size, with_labels=True, ax=ax)
    ax.set_title('Degree Centrality')

    # Set node size based on closeness centrality
    node_size = [v * 1000 for v in closeness_centrality.values()]

    # Draw the graph for closeness centrality
    fig, ax = plt.subplots()

    nx.draw(G, pos=nx.kamada_kawai_layout(G), node_size=node_size, with_labels=True, ax=ax)
    ax.set_title('Closeness Centrality')

    # Set node size based on betweenness centrality
    node_size = [v * 1000 for v in betweenness_centrality.values()]

    # Draw the graph for betweenness centrality
    fig, ax = plt.subplots()
    nx.draw(G, pos=nx.kamada_kawai_layout(G), node_size=node_size, with_labels=True, ax=ax)
    ax.set_title('Betweenness Centrality')

    # Set node size based on eigenvector centrality
    node_size = [v * 1000 for v in eigenvector_centrality.values()]

    # Draw the graph for eigenvector centrality
    fig, ax = plt.subplots()
    nx.draw(G, pos=nx.kamada_kawai_layout(G), node_size=node_size, with_labels=True, ax=ax)
    ax.set_title('Eigenvector Centrality')

    # Draw the graph with communities shaded in different colors
    fig, ax = plt.subplots()
    pos = nx.kamada_kawai_layout(G)
    colors = ['r', 'g', 'b', 'y', 'c', 'm']
    for i, community in enumerate(communities):
        nx.draw_networkx_nodes(G, pos, nodelist=community, node_color=colors[i % len(colors)], ax=ax)

    nx.draw_networkx_edges(G, pos, ax=ax)
    nx.draw_networkx_labels(G, pos, ax=ax)
    ax.set_title('Communities')

    plt.show()

When I try calling the function with my input file:

calculate_network_properties('adjacency matrix.txt')

I get an output images that looks like:

All the nodes are packed together and thus the architecture of my networks cannot be seen. How can I fix the problem?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Diego RM
  • 21
  • 2
  • Welcome to Stack Overflow. Please read [ask] and make sure to **ask a question** after clearly describing a problem. Make sure to explain directly: What happens when you run the code? What is supposed to happen instead, and **how is that different**? Then, before asking, [please try](https://meta.stackoverflow.com/questions/261592) to look for an existing Q&A, [locate](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) a problem by carefully checking what happens when the code runs, step by step, and produce a [mre]. – Karl Knechtel Apr 15 '23 at 04:58
  • For example, does the problem still occur if you only draw one set of nodes? Can you make it draw *any* networkx graph the way you want? Did you try to check the data - for example, does `adj_matrix` look right after `adj_matrix = np.loadtxt(file_path)`? Finally: please note well that this is **not a discussion forum**. We [assume your thanks and do not want it stated](https://meta.stackoverflow.com/questions/288160); we want question titles to **describe** the problem rather than advertising "I need help"; and we [don't offer "help" anyway](https://meta.stackoverflow.com/questions/284236). – Karl Knechtel Apr 15 '23 at 05:02
  • I tried to edit the question to show proper style for asking questions on Stack Overflow. Please carefully note all the changes, then try to prepare a [mre] and provide missing information. – Karl Knechtel Apr 15 '23 at 05:06
  • Does your graph have multiple components? I don't think that the KK layout is defined for multi-component graphs, which may be the cause of the terrible node layout. If that is the case, you may need to plot the components separately / arrange them explicitly. Some suggestions on how to do that can be found [here](https://stackoverflow.com/a/53156709/2912349). – Paul Brodersen Apr 18 '23 at 10:26

0 Answers0