Skip to content
Advertisement

How to update a NetworkX plot in real-time?

I’m trying to update a networkx plot using matplotlib in a canvas, but it adds a new plot to the graph each time instead of updating the graph below, I had to add the call to nx.draw_networkx() function to get it to update and I’m not sure if this is part of the issue. Example Code:

import psutil
import tkinter as tk
from tkinter import *
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg
)

root = Tk()
root.title("Hello")

mlist = psutil.net_connections(kind="all")
fig = plt.figure(frameon=True, figsize=(5,1), dpi=100)
canvas = FigureCanvasTkAgg(fig, root)
Node = nx.Graph()

for v, val in enumerate(mlist):
    if val[4] != () and val[4][0] != "127.0.0.1":
        print(str(val[4][0]) + " - " + str(val[6]))
        print(psutil.Process(val[6]).name())
        Node.add_node(str(val[4][0]))
        Node.add_edge(str(val[4][0]), "localhost")

plt.gca().set_facecolor("grey")
fig.set_facecolor("black")

nx.draw_networkx(Node, pos=nx.spring_layout(Node, 25), alpha=1,
                 with_labels=False, node_size=100, node_color="green")

canvas.draw()
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=True)

def Add():
    Node.add_node(str("LOL"))
    nx.draw_networkx(Node, pos=nx.spring_layout(Node, 25), alpha=1, 
                     with_labels=False, node_size=100,
                         node_color="blue")
    canvas.draw()

ex = tk.Button(root, text="Update", command=lambda: Add())
ex.pack(side="bottom")

root.mainloop()

Advertisement

Answer

I have found a similar question and answer after a lengthy search on this question here however for clarity and because i also used code from elsewhere you must use the G.clear() to clear the current nodes and edges from the graph. plt.clf() to clear the figure from the canvas followed by canvas.draw to draw the new or update graph onto the canvas.

The use of the 3 functions above will depend on your individual use.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement