Python 图和轴对象
Python figure and axes object
我有一个关于 matplotlib
Python 模块的大问题尚未解决。
如果我创建一个名为 [Figure1]
的图,有 2 个轴 [Ax1, Ax2]
,和另一个图 [Figure2]
,是否有函数或方法可以让我导出 Ax1
对象从 Figure1
重绘到 Figure2
对象?
一般情况下,坐标轴绑定到图形。原因是,matplotlib 通常会在后台执行一些操作,以使它们在图中看起来更好看。
有some hacky ways around this, also this one,但普遍的共识似乎是应该避免尝试复制坐标轴。
另一方面,这根本不是问题或限制。
您始终可以定义一个函数来绘制并在多个图形上使用它,如下所示:
import matplotlib.pyplot as plt
def plot1(ax, **kwargs):
x = range(5)
y = [5,4,5,1,2]
ax.plot(x,y, c=kwargs.get("c", "r"))
ax.set_xlim((0,5))
ax.set_title(kwargs.get("title", "Some title"))
# do some more specific stuff with your axes
#create a figure
fig, (ax1, ax2) = plt.subplots(1,2)
# add the same plot to it twice
plot1(ax1)
plot1(ax2, c="b", title="Some other title")
plt.savefig(__file__+".png")
plt.close("all")
# add the same plot to a different figure
fig, ax1 = plt.subplots(1,1)
plot1(ax1)
plt.show()
我有一个关于 matplotlib
Python 模块的大问题尚未解决。
如果我创建一个名为 [Figure1]
的图,有 2 个轴 [Ax1, Ax2]
,和另一个图 [Figure2]
,是否有函数或方法可以让我导出 Ax1
对象从 Figure1
重绘到 Figure2
对象?
一般情况下,坐标轴绑定到图形。原因是,matplotlib 通常会在后台执行一些操作,以使它们在图中看起来更好看。
有some hacky ways around this, also this one,但普遍的共识似乎是应该避免尝试复制坐标轴。
另一方面,这根本不是问题或限制。
您始终可以定义一个函数来绘制并在多个图形上使用它,如下所示:
import matplotlib.pyplot as plt
def plot1(ax, **kwargs):
x = range(5)
y = [5,4,5,1,2]
ax.plot(x,y, c=kwargs.get("c", "r"))
ax.set_xlim((0,5))
ax.set_title(kwargs.get("title", "Some title"))
# do some more specific stuff with your axes
#create a figure
fig, (ax1, ax2) = plt.subplots(1,2)
# add the same plot to it twice
plot1(ax1)
plot1(ax2, c="b", title="Some other title")
plt.savefig(__file__+".png")
plt.close("all")
# add the same plot to a different figure
fig, ax1 = plt.subplots(1,1)
plot1(ax1)
plt.show()