[英]how to plot different plot in a single plot matplotlib
我以这种方式创建了 2 个不同的 plot:
def first():
fig, axes = plt.subplots(1, figsize=(10, 5))
...
...
return fig, axes
def second():
fig, axes = plt.subplots(1, figsize=(10, 5))
...
...
return fig, axes
我想做的是将这两个地块“收集”在一个地块中。 我尝试这些解决方案:
1:
fig, ax = plt.subplots(2, figsize=(15, 20))
ax[0].plot = first()
ax[1].plot = second()
plt.show()
2:
fig, ax = plt.subplots(2, figsize=(15, 20))
ax[0].plot = first()
ax[1].plot = second()
for ax in ax:
ax.label_outer()
plt.show()
但任何时候我都会得到 3 个不同的数字:一个有 2 个轴但为空的数字 和右边的 2 个数字 plot 但不是我想去的地方
有人可以帮助并建议我在代码中出错的地方吗? 谢谢
这是一个简单的示例,说明您如何继续实现您的目标。
让我们创建一个具有axe
开关的 function 以应对现有的 matplotlib 斧头,或者在缺少时创建它。
import matplotlib.pyplot as plt
def first(x, y, axe=None):
if axe is None:
fig, axe = plt.subplots()
axe.plot(x, y)
axe.set_ylabel("First")
axe.grid()
return axe
同样,我们创建第二个 function:
def second(x, y, axe=None):
if axe is None:
fig, axe = plt.subplots()
axe.plot(x, y)
axe.set_ylabel("Second")
axe.grid()
return axe
我们为显示目的创建了一些合成数据:
import numpy as np
t = np.linspace(0, 2*np.pi, 250)
x1 = 3*np.sin(5*t)
x2 = 0.5*np.cos(15*t)
然后是魔术,我们创建两个轴并发送对它们各自函数的引用:
fig, axe = plt.subplots(2, 1, sharex=True, sharey=True)
first(t, x1, axe=axe[0])
second(t, x2, axe=axe[1])
之后我们仍然可以向轴添加功能:
axe[0].set_title("Some functional plots")
axe[1].set_xlabel("Time")
最终结果如下所示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.