Home > Software engineering >  Plotting multiple plots and text with networkx and matplotlib
Plotting multiple plots and text with networkx and matplotlib

Time:11-25

I am calling the function nx.draw to plot a graph eg:

enter image description here

I would like to make a plot that graphs three such graphs in a line, with a = and \cup symbol in between to symbolize that one is the union of the other two.

For example something like this:

enter image description here

How can I make this with matplotlib?

I tried

import networkx as nx
import matplotlib.pyplot as plt

G=nx.grid_2d_graph(1,5)
plt.subplot(151)
draw_model(composite_argument)
ax = plt.subplot(152)
ax.text(60, 60,"=")
ax.set_xlim(0, 100)
ax.set_ylim(0, 100)
plt.subplot(153)
draw_model(argument1)
ax = plt.subplot(154)
ax.text(60, 60,"U")
ax.set_xlim(0, 100)
ax.set_ylim(0, 100)
plt.subplot(155)
draw_model(argument2)

which results in a very weird plot

enter image description here

CodePudding user response:

You are clearly doing something wrong inside draw_model(). Maybe you call plt.figure() or plt.show()?

Anyway, the recommended way to create subplots is via plt.subplots(...). And the recommended way to let networkx draw into a subplot is via nx.draw(...., ax=...).

Note that, by default, a subplot has axis limits 0 and 1 both in x and in y direction. Many plotting functions automatically update the axis limits, but ax.text() doesn't (which enables annotations close to the borders without moving them).

Here is some example code.

from matplotlib import pyplot as plt
import networkx as nx

fig, axs = plt.subplots(ncols=5, figsize=(14, 4), gridspec_kw={'width_ratios': [4, 1, 4, 1, 4]})

nx.draw_circular(nx.complete_graph(5), ax=axs[0])

axs[1].text(0.5, 0.5, '<', size=50, ha='center', va='center')
axs[1].axis('off')

nx.draw_circular(nx.complete_graph(7), ax=axs[2])

axs[3].text(0.5, 0.5, '<', size=50, ha='center', va='center')
axs[3].axis('off')

nx.draw_circular(nx.complete_graph(9), ax=axs[4])

plt.show()

networkx plots into subplots

  • Related