python独立图形_python - 如何在Matplotlib的子图中独立绘制同一图形?

matplotlib: combine different figures and put them in a single subplot sharing a common legend

(1个答案)

6年前关闭。

我正在用Python编写一个生成许多图形的程序。其中一些是有趣的,既独立的,也比较其他图形。生成这些图(就运行时而言)是昂贵的,我不想多次生成它们。有没有办法生成一个情节一次,并且它是子情节的一部分?

我基本上在寻找一个替代方案:

#generate standalone graphs

pylab.figure()

generate_plot0()

pylab.figure()

generate_plot1()

#generate subplot

pylab.figure()

subplot(121)

generate_plot0()

subplot(122)

generate_plot1()

但不呼叫两次。

有什么好办法吗?

最佳答案

一般来说,matplotlib艺术家不能在多个轴上,轴也不能在多个图形中。(在某些情况下,您可以违反这些规则中的某些规则,但通常不会起作用。)

因此,简短的回答是不。

但是,您可能会考虑如下内容。您可以将所讨论的绘图作为子块,然后绑定click/keypress/whatever以隐藏所有其他子块,并使选定的轴临时填充整个图形。

举个简单的例子:import numpy as np

import matplotlib.pyplot as plt

def main():

subplots = ZoomingSubplots(2, 2)

colors = ['red', 'green', 'blue', 'cyan']

for ax, color in zip(subplots.axes.flat, colors):

data = (np.random.random(200) - 0.5).cumsum()

ax.plot(data, color=color)

subplots.fig.suptitle('Click on an axes to make it fill the figure.\n'

'Click again to restore it to its original position')

plt.show()

class ZoomingSubplots(object):

def __init__(self, *args, **kwargs):

"""All parameters passed on to 'subplots`."""

self.fig, self.axes = plt.subplots(*args, **kwargs)

self._zoomed = False

self.fig.canvas.mpl_connect('button_press_event', self.on_click)

def zoom(self, selected_ax):

for ax in self.axes.flat:

ax.set_visible(False)

self._original_size = selected_ax.get_position()

selected_ax.set_position([0.125, 0.1, 0.775, 0.8])

selected_ax.set_visible(True)

self._zoomed = True

def unzoom(self, selected_ax):

selected_ax.set_position(self._original_size)

for ax in self.axes.flat:

ax.set_visible(True)

self._zoomed = False

def on_click(self, event):

if event.inaxes is None:

return

if self._zoomed:

self.unzoom(event.inaxes)

else:

self.zoom(event.inaxes)

self.fig.canvas.draw()

if __name__ == '__main__':

main()

初始状态

点击子批次后

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值