[英]matplotlib: change active axes
我有多个对象可以可视化不同的事物。 它们都被传递到单个 Figure 实例的引用并创建自己的轴对象(同时只有一个处于活动状态)
演示代码是:
import numpy as np
import matplotlib.pyplot as plt
# the visualization objects are jupyter widgets in production code
%matplotlib widget
plt.ioff()
def update_fig(f):
f.canvas.draw()
f.canvas.flush_events()
f = plt.figure()
# first visualizer is created and plots into the figure
ax1 = f.add_subplot(1,1,1, label="visualizer_1")
img1 = np.random.randint(0, 256, (20, 20, 3))
vis1 = ax1.imshow(img1)
update_fig(f)
# second visualizer is created and plots into the figure
ax2 = f.add_subplot(1,1,1, label="visualizer_2")
vis2 = ax2.plot(np.linspace(0, 5), 2 * np.linspace(0, 5))
update_fig(f)
然后如何切换要在图中显示的轴? 已经尝试plt.sca(ax1)
返回到第一个可视化,但没有奏效。
当然,我可以为每个可视化对象使用不同的图形,但由于我有很多,我宁愿避免这种情况。
您可以随时使用Axes.set_visible([True|False])
来显示或隐藏特定轴。
f = plt.figure()
# first visualizer is created and plots into the figure
ax1 = f.add_subplot(1,1,1, label="visualizer_1")
img1 = np.random.randint(0, 256, (20, 20, 3))
vis1 = ax1.imshow(img1)
update_fig(f)
# second visualizer is created and plots into the figure
ax1.set_visible(False)
ax2 = f.add_subplot(1,1,1, label="visualizer_2")
vis2 = ax2.plot(np.linspace(0, 5), 2 * np.linspace(0, 5))
update_fig(f)
ax2.set_visible(False) # hide ax2
ax1.set_visible(True) # show ax1 again.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.