在for循环中绘制单个图上的多个图 - Python

时间:2017-09-05 10:17:25

标签: python-3.x matplotlib plot

我已审核了对此问题的回复:How would I iterate over a list of files and plot them as subplots on a single figure?

但是如何实现我的目标并不是明智之举。我想将具有不同x轴的多个数据集绘制到Python中的单个图形上。我在下面包含了我的代码片段,它对数据集执行FFT,然后计算3个Butterworth滤波器输出。理想情况下,我希望将所有绘制在一个图上,我试图在下面的代码中实现。 for循环计算3个Butterworth滤波器输出,上面的代码--FFT和下面的代码试图将FFT曲线和sqrt(0.5)线附加到先前生成的图形以供显示。

任何指示或建议都将受到赞赏。

"""Performs a Fast Fourier Transform on the data specified at the base of the code"""
def FFT(col):
    x = io2.loc[1:,'Time']
    y = io2.loc[1:,col]
    # Number of samplepoints
    #N = 600
    N = pd.Series.count(x)
    N2 = int(N/2)
    # sample spacing
    #T = 1.0 / 800.0
    T = 1/(io2.loc[2,'Time'] - io2.loc[1,'Time'])
    #x = np.linspace(0.0, N*T, N)
    #y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
    yf = scipy.fftpack.fft(y)
    xf = np.linspace(0.0, 1.0/(2.0*T), N2)

fig=plt.figure()
plt.clf()
i=1
for order in [3, 6, 9]:
    ax=fig.add_subplot(111, label="order = %d" % order)
    b, a = butter_lowpass(cutoff, fs, order=order)
    w, h = freqz(b, a, worN=2000)

    ax.plot((fs * 0.5 / np.pi) * w, abs(h))
    i=i+1

ax4=fig.add_subplot(111, label='sqrt(0.5)', frame_on=False)
ax5=fig.add_subplot(111, label="FFT of "+col, frame_on=False)

ax4.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)], '--')
ax5.plot(xf, 2.0/N * np.abs(yf[:N2]))
plt.xlabel('Frequency (Hz)')
plt.ylabel('Gain')
plt.grid(True)
plt.legend(loc='best')

#fig, ax = plt.subplots()
#ax.plot(xf, 2.0/N * np.abs(yf[:N2]), label="FFT of "+col)
plt.axis([0,5000,0,0.1])
#plt.xlabel('Frequency (Hz)')
#plt.ylabel('Amplitude (mm)')
#plt.legend(loc=0)
plt.show()

return

亲切的问候,

1 个答案:

答案 0 :(得分:0)

在这里,您可以找到如何使用不同的 x y 数据集绘制多条线的最小示例。每次键入add_subplot(111)时,您都在重新创建绘图。相反,您应多次致电plot。我添加了一个包含多行的单个图的示例,以及每行一个子图的示例。

import numpy as np
import matplotlib.pyplot as plt

x1 = np.arange(0, 10, 1)
x2 = np.arange(3, 12, 0.1)
x3 = np.arange(2, 8, 0.01)

y1 = np.sin(x1)
y2 = np.cos(x2**0.8)
y3 = np.sin(4.*x3)**3

data = []
data.append((x1, y1, 'label1'))
data.append((x2, y2, 'label2'))
data.append((x3, y3, 'label3'))

# All lines in one plot.
plt.figure()
for n in data:
    plt.plot(n[0], n[1], label=n[2])
plt.legend(loc=0, frameon=False)

# One subplot per data set.
cols = 2
rows = len(data)//2 + len(data)%2
plt.figure()
gs = plt.GridSpec(rows, cols)
for n in range(len(data)):
    i = n%2
    j = n//2
    plt.subplot(gs[j,i])
    plt.plot(data[n][0], data[n][1])
    plt.title(data[n][2])
plt.tight_layout()
plt.show()