Simple knowledge graph visualization + drawing nx.Graph() reports an error TypeError: '_AxesStack' object is not callable

An error is reported when drawing nx.Graph TypeError: '_AxesStack' object is not callable

write on top

Realize a simple visualization function of knowledge graph.
The NetworkX library is used to build a knowledge map, and the matplotlib library is used to draw graphics.

In a few days, I will publish an article about #总是noe4j智能知识图#,
and the details are still being optimized

As an aside, building a knowledge graph is really slow, especially for automatically building the relationship between entities. The code takes a long time to run,
and it’s not considered the innovation point in the paper. It feels a bit tasteless

Knowledge Map Visualization

Knowledge map visualization is to display the data of knowledge map in a graphical way, so as to understand, analyze and explore the relationship and information in knowledge map more intuitively.

Through the interactive graphical interface, the relationships and concepts in the knowledge graph can be explored and analyzed, and can be freely navigated and browsed from the macro to the micro.

It can be applied to search engines, recommendation systems, medical research, business intelligence, social networks, financial analysis and other fields.

expected

Draw the graph of nx.Graph()

report error

TypeError: ‘_AxesStack’ object is not callable

nx.draw(graph, pos, with_labels=True, node_size=3000, font_size=12, node_color='skyblue', font_weight='bold', alpha=0.8, linewidths=0, edge_color='gray')
      9 plt.title("Knowledge Graph")
     10 plt.show()

File D:\Program\Anaconda\lib\site-packages\networkx\drawing\nx_pylab.py:113, in draw(G, pos, ax, **kwds)
    111 cf.set_facecolor("w")
    112 if ax is None:
--> 113     if cf._axstack() is None:
    114         ax = cf.add_axes((0, 0, 1, 1))
    115     else:

TypeError: '_AxesStack' object is not callable

<Figure size 1000x800 with 0 Axes>

possible reason

This error is due to calling a non-callable object while drawing the graph _AxesStack, usually this is related to a conflict with a variable or function name. pltCheck to see if there is a variable or function named or used elsewhere in your code axthat is causing this error.

Here are some common causes and solutions that can cause problems:

  1. Make sure pltthat is a Matplotlib pyplot object and has not been redefined elsewhere. pltYou can try adding at the beginning of your code before using import matplotlib.pyplot as plt.

  2. Make sure the variable name is not axassigned as an Axes object. The Axes object is returned by functions such as plt.subplots()or , so if used as an ordinary variable, it may cause conflicts.plt.add_axes()ax

  3. It could be that some other part of the code has modified Matplotlib's default behavior so that is AxesStacknot callable. Please check for any customizations or modifications involving Matplotlib before plotting the graph.

After confirming the above problems, you can try to modify the code and ensure that the drawing part does not conflict with the problems mentioned before, so as to avoid the occurrence of this error.

original code

Defines a function called draw_graph that takes a graph object as an argument and displays the graph in a plot. The main function creates an empty graph object and adds some nodes and edges.

import networkx as nx
import matplotlib.pyplot as plt

def draw_graph(graph):
    pos = nx.spring_layout(graph, seed=42)
    # 下面这行代码有问题,已修改为
    # fig, ax = plt.subplots(figsize=(10, 8))
    plt.figure(figsize=(10, 8))
    nx.draw(graph, pos, with_labels=True, node_size=3000, font_size=12, node_color='skyblue', font_weight='bold', alpha=0.8, linewidths=0, edge_color='gray')
    plt.title("Knowledge Graph")
    plt.show()

def main():
    # 假设已构建好知识图谱
    graph = nx.Graph()
    graph.add_nodes_from(["Entity1", "Entity2", "Entity3"])
    graph.add_edges_from([("Entity1", "Entity2"), ("Entity2", "Entity3")])

    draw_graph(graph)

if __name__ == "__main__":
    main()

Cause Confirmation

What I encountered was the second reason: because of a conflict with Matplotlib's Axes object (ax).

To get around this, try specifying the Axes object explicitly when drawing the graph. Create a new Axes object in plt.subplots() and pass it to the nx.draw() function.

resolved code

import networkx as nx
import matplotlib.pyplot as plt

def draw_graph(graph):
    pos = nx.spring_layout(graph, seed=42)  # You can use different layout algorithms

    fig, ax = plt.subplots(figsize=(10, 8))
    nx.draw(graph, pos, with_labels=True, node_size=3000, font_size=12, node_color='skyblue', font_weight='bold', alpha=0.8, linewidths=0, edge_color='gray', ax=ax)
    ax.set_title("Knowledge Graph")
    plt.show()

def main():
    # 假设已构建好知识图谱
    graph = nx.Graph()
    graph.add_nodes_from(["Entity1", "Entity2", "Entity3"])
    graph.add_edges_from([("Entity1", "Entity2"), ("Entity2", "Entity3")])

    draw_graph(graph)

if __name__ == "__main__":
    main()

solve!

insert image description here

Guess you like

Origin blog.csdn.net/wtyuong/article/details/131877783