我在尝试将简单生成的图表与图中的按钮分开时遇到问题。
基本上,这个想法是只要按下任一按钮,图表中的节点就应该改变颜色。我无法将图表与“下一步”按钮分开。而且每当按下按钮时,按钮内的图形似乎都会被取代。
有什么想法可以分离图形并防止按下按钮时图形重叠?
这是一个示例代码:
import matplotlib.pyplot as plt
import networkx as nx
from matplotlib.widgets import Button
from itertools import product
# Create the 2D graph and define the range
N = 6
G = nx.Graph()
for i in range(1, (N*N)+1):
G.add_node(i)
def update_node_colors(colors):
node_pos = list(product(range(0, N), repeat=2))
pos = dict( (i + 1 + (N - 1 - j) * N, (i,j)) for i,j in node_pos )
nx.draw(G, pos, with_labels=True, node_color=colors)
plt.draw()
def prev_button(event):
colors = ["yellow" for _ in G.nodes()]
update_node_colors(colors)
def next_button(event):
colors = ["red" for _ in G.nodes()]
update_node_colors(colors)
fig, ax = plt.subplots(1, 1, figsize=(7,6))
# Give position to nodes
node_pos = list(product(range(0, N), repeat=2))
pos = dict( (i + 1 + (N - 1 - j) * N, (i,j)) for i,j in node_pos )
nx.draw(G, pos, with_labels=True)
plt.subplots_adjust(bottom=0.2)
ax_prev = plt.axes([0.85, 0.15, 0.15, 0.07])
button_prev = Button(ax_prev, "Prev", color = "green", hovercolor = "blue")
button_prev.on_clicked(prev_button)
ax_next = plt.axes([0.85, 0.05, 0.15, 0.07])
button_next = Button(ax_next, "Next", color = "orange", hovercolor = "red")
button_next.on_clicked(next_button)
#plt.axis('off')
plt.show()
您正在创建一个图形和一个轴:
fig, ax = plt.subplots(1, 1, figsize=(7,6))
稍后,您通过 ax_prev
创建另外 2 个轴实例(ax_next
和 plt.axes()
)。
当您执行此操作时,您的程序将焦点切换到最后创建的轴实例。在这种情况下,这是 ax_next
。这意味着 nx.draw()
现在将使用该轴进行绘制。
要将焦点切换回主实例
ax
,您可以使用 plt.sca(ax)
。
然后 nx.draw()
将使用选定的主轴 ax
。
最终代码可能如下所示:
def update_node_colors(colors):
plt.sca(ax)
node_pos = list(product(range(0, N), repeat=2))
pos = dict( (i + 1 + (N - 1 - j) * N, (i,j)) for i,j in node_pos )
nx.draw(G, pos, with_labels=True, node_color=colors)
plt.draw()