Python 如何在子地块中绘制地物(Matplotlib)
我知道在一个图形中绘制多个图形有多种方法。其中一种方法是使用轴,例如Python 如何在子地块中绘制地物(Matplotlib),python,matplotlib,plot,Python,Matplotlib,Plot,我知道在一个图形中绘制多个图形有多种方法。其中一种方法是使用轴,例如 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(figur
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)
这不起作用,但我怎样才能使它起作用?有没有一种方法可以将图形放在子图中,或者有一种解决方法可以在一个整体图形中绘制多个图形
非常感谢您在这方面的任何帮助。
提前感谢您的评论。一个可能的解决方案是
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)
但是,为了工作,数据1,2必须是数据。如果您有一个已经为您绘制数据的函数,我建议在函数中包含一个轴
参数。比如说
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])
如果目标只是自定义单个子绘图,为什么不更改函数以动态更改当前图形,而不是返回图形。从和,可以在绘图时更改绘图设置吗
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()
也许我不完全理解你的问题。这是“美化”功能复杂吗?…非常感谢你的回答,但这正是我试图回避的问题。我不想打印数据,但想打印一个易于检索的图形对象。@阿恩:我从来没有遇到过一个内置函数,它将两个图形包含在一个图形中。因此,有必要从图形对象中提取所有数据,并使用多个轴在新图形中再次打印它们。虽然这是可能的,但它比简单地给出轴作为参数要复杂得多。