您得到几个图的原因是在每个循环中,您调用plt.figure,这将创建一个新的图形窗口。把这个放在循环之前,在循环中创建新的sublots。
您只需通过[1, 2, 3, ..., columns]中的m的值。这是内置的^{},其中range(columns)给出{},所以{}就是您想要的。您不需要手动增加m,也不需要使用p来停止循环:一旦m的每个值都在范围内,这两种情况都会自动发生。
要获得数据的第m列,只需在“column”维度中切片,这是第二个维度:data[:, m]给出第m列中的所有行。空的:表示“所有行”,而m表示“列m”。(你可以像列表一样做完整的切片,但是在多个维度上)。有关详细信息,请参见here和here。
对于子地块,您必须更改每个地块的第一个参数。你可以这样称呼它:fig.add_subplot(nrows, ncols, plot_number)。所以您希望plot_number在循环中是m。
所有这些加在一起:import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt('csv_file',delimiter=',', dtype = float)
columns = data.shape[1] - 1 # a numpy array's `shape` is (rows, columns, etc). I am subtracting the x column.
nrows, ncols = 4, 2 # the product of these should be number of plots (I'm assuming columns=8)
fig = plt.figure()
x = data[:, 0] # same as [row[0] for row in data], and doesn't change in loop, so only do it once.
for m in range(1, columns+1): # this loops from 1 through columns
y = data[:, m] # same as [row[m] for row in data]
ax = fig.add_subplot(nrows, ncols, m, axisbg = 'w')
ax.plot(x, y, lw=1.3)
plt.show() # after loop finishes, only need to show once.