在matplotlib中循环

时间:2012-12-10 11:03:10

标签: python loops matplotlib

我试图在一组轴上绘制多个图形。

我有一个2D数组数据,想要将其分解为111个1D数组并绘制它们。以下是我的代码示例:

from numpy import *
import matplotlib.pyplot as plt

x = linspace(1, 130, 130) # create a 1D array of 130 integers to set as the x axis
y = Te25117.data # set 2D array of data as y
plt.plot(x, y[1], x, y[2], x, y[3]) 

这段代码工作正常,但是我看不到编写一个循环的方法,这个循环将在绘图本身内循环。如果我每次明确地写一个数字1到111,我只能使代码工作,这是不理想的! (我需要循环的数字范围是1到111.)

2 个答案:

答案 0 :(得分:3)

让我猜猜......长时间的matlab用户? 如果您不创建新图,Matplotlib会自动为当前图添加线图。所以你的代码可以很简单:

from numpy import *
import matplotlib.pyplot as plt

x = linspace(1, 130, 130) # create a 1D array of 130 integers to set as the x axis
y = Te25117.data # set 2D array of data as y
L = len(y) # I assume you can infere the size of the data in this way...
#L = 111 # this is if you don't know any better
for i in range(L)
    plt.plot(x, y[i], color='mycolor',linewidth=1) 

答案 1 :(得分:0)

import numpy as np
import matplotlib.pyplot as plt
x = np.array([1,2])
y = np.array([[1,2],[3,4]])

In [5]: x
Out[5]: array([1, 2])

In [6]: y
Out[6]: 
array([[1, 2],
       [3, 4]])

In [7]: for y_i in y:
  ....:     plt.plot(x, y_i)

将这些绘制在一个图中。