使用不同的数据自动填充子图

时间:2015-09-16 15:41:10

标签: python matplotlib

我正在尝试执行以下操作:

import matplotlib.pyplot as plt
import numpy as np
#data
x = np.linspace(0, 2 * np.pi, 400)
y1 = np.sin(x)
y2 = np.sin(x**2)
y3 = np.cos(x**2)
#plot       
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
ax1.plot(x, y1)
ax1.set_title('lalalala')
ax2.plot(x, y2)
ax3.plot(x, y3)
f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)

不是手动输入ax1到ax3和y1到y3,我想知道是否有任何方法可以绕过斧头和y来填充图。我知道这个post,但那里给出的最佳答案并不是循环数据。谢谢!

1 个答案:

答案 0 :(得分:1)

当然,只需输入您想要的所有列表并在循环中添加子图:

import matplotlib.pyplot as plt
import numpy as np
#data
x = np.linspace(0, 2 * np.pi, 400)

y = [np.sin(x), np.sin(x**2), np.cos(x**2)]
title = ['y1','y2','y3']

#plot       
numPlots = len(y)
f = plt.figure()
ax = []
for i in range(numPlots):
    ax.append(f.add_subplot(numPlots,1,i+1))
    ax[i].plot(x, y[i])
    ax[i].set_title(title[i])
    f.subplots_adjust(hspace=0.3)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
plt.show()

Subplots created in a loop