如何在子图中绘制图形

3
我知道有多种方法可以在一个图中绘制多个图形。其中一种方法是使用坐标轴,例如。
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([range(8)])
ax.plot(...)

由于我有一个可以美化图形并返回图像的函数,所以我想使用该图像来绘制我的子图。它应该看起来类似于这样:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(figure1) # where figure is a plt.figure object
ax.plot(figure2)

这个不起作用,但是如何让它起作用呢?有没有办法在子图中放置图形,或者通过某种方法在一个整体图中绘制多个图形?

对此的任何帮助都将不胜感激。 提前感谢您的评论。

2个回答

4

如果目标只是定制单个子图,为什么不改变您的函数以在运行时更改当前的图形而不是返回一个图形。从matplotlibseaborn,您可以在绘制时更改图形设置吗?

import numpy as np
import matplotlib.pyplot as plt

plt.figure()

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'ko-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')

import seaborn as sns

plt.subplot(2, 1, 2)
plt.plot(x2, y2, 'r.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')

plt.show()

也许我没有完全理解你的问题。这个“美化”功能很复杂吗?...

1
一个可能的解决方案是:
import matplotlib.pyplot as plt

# Create two subplots horizontally aligned (one row, two columns)
fig, ax = plt.subplots(1,2)
# Note that ax is now an array consisting of the individual axis

ax[0].plot(data1) 
ax[1].plot(data2)

然而,为了使用data1,2,需要有数据。如果您已经有一个绘制数据的函数,建议在函数中包含一个axis参数。例如:

def my_plot(data,ax=None):
    if ax == None:
        # your previous code
    else:
        # your modified code which plots directly to the axis
        # for example: ax.plot(data)

然后您可以像这样绘制它:
import matplotlib.pyplot as plt

# Create two subplots horizontally aligned
fig, ax = plt.subplots(2)
# Note that ax is now an array consisting of the individual axis

my_plot(data1,ax=ax[0])
my_plot(data2,ax=ax[1])

非常感谢您的回答,但这正是我试图规避的问题。我不想绘制数据,而是要获取一个可用的图形对象。 - Arne
1
@Arne:我从未遇到过一个内置函数可以将两个图形合并成一个。因此,需要从图形对象中提取所有数据,并使用多个轴在新图形中重新绘制它们。虽然这可能是可行的,但比起简单地将轴作为参数传递更加复杂。 - plonser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接