如何在matplotlib中索引n组4列以绘制多个图?

3 投票
3 回答
557 浏览
提问于 2025-04-17 08:11

我想知道在Python中应该如何以编程的方式索引或访问一些数据。
我有一些列状数据:深度、温度、梯度和伽马值,这些数据是针对一组钻孔的。有n个钻孔。我有一个表头,列出了钻孔的名称和数字ID。举个例子:

Bore_name,Bore_ID,,,Bore_name,Bore_ID,,,, ... 
<a row of headers>
depth,temp,gradient,gamma,depth,temp,gradient,gamma ...

我不知道该如何索引这些数据,除了用比较粗暴的方式逐个遍历:

with open(filename,'rU') as f:
    bores = f.readline().rstrip().split(',')   
    headers = f.readline().rstrip().split(',')


# load from CSV file, missing values are empty 'cells'
tdata = numpy.genfromtxt(filename, skip_header=2, delimiter=',', missing_values='', filling_values=numpy.nan)

for column in range(0,numpy.shape(tdata)[1],4):  
    # plots temperature on x, depth on y
    pl.plot(tdata[:,column+1],tdata[:,column], label=bores[column])
    # get index at max depth
    depth = numpy.nanargmin(tdata[:,column])
    # plot text label at max depth (y) and temp at that depth (x)
    pl.text(tdata[depth,column+1],tdata[depth,column],bores[column])

这样做看起来还算简单,但我最近在使用R语言,已经有点习惯了通过类和子类来引用数据对象,这些类和子类是从表头中解析出来的。

3 个回答

1

这里有一些给行和列命名的常用表达:

row0, row1 = np.ones((2,5))

for col in range(0, tdata.shape[1], 4):
   depth,temp,gradient,gamma = tdata[:, col:col+4] .T
   pl.plot( temp, depth )

另外,您可以查看 namedtuple

from collections import namedtuple
Rec = namedtuple( "Rec", "depth temp gradient gamma" )
r = Rec( *tdata[:, col:col+4].T )
print r.temp, r.depth

datarray(感谢Doug)确实更通用。

1

你可以把每个钻孔的数据放到一个 dict(字典)里,使用钻孔的ID作为键,值则是一个字典,里面的标题作为键。大概是这样的:

data = {boreid1:{"temp":temparray, ...}, boreid2:{"temp":temparray}}

用这种方法,从文件读取数据可能会稍微麻烦一些,但在绘图时你可以这样做:

pl.plot(data[boreid]["temperature"], data[boreid]["depth"])
1

如果你喜欢R语言中的data.table,那么在NumPy中也有一些尝试去实现类似的功能,这些尝试通过NumPy核心的额外类和一些外部的Python库来完成。我觉得最有前景的一个库是由Fernando Perez开发的datarray。下面是它的工作原理。

>>> # create a NumPy array for use as our data set
>>> import numpy as NP
>>> D = NP.random.randint(0, 10, 40).reshape(8, 5)

>>> # create some generic row and column names to pass to the constructor
>>> row_ids = [ "row{0}".format(c) for c in range(D1.shape[0]) ]
>>> rows = 'rows_id', row_ids

>>> variables = [ "col{0}".format(c) for c in range(D1.shape[1]) ]
>>> cols = 'variable', variables

你可以通过调用构造函数来创建一个DataArray实例,并传入一个普通的NumPy数组和一个元组列表——每个轴对应一个元组。因为这里的维度是2(ndim = 2),所以列表中会有两个元组,每个元组包含一个轴标签(字符串)和该轴的标签序列(列表)。

>>> from datarray.datarray import DataArray as DA
>>> D1 = DA(D, [rows, cols])

>>> D1.axes
      (Axis(name='rows', index=0, labels=['row0', 'row1', 'row2', 'row3', 
           'row4', 'row5', 'row6', 'row7']), Axis(name='cols', index=1, 
           labels=['col0', 'col1', 'col2', 'col3', 'col4']))

>>> # now you can use R-like syntax to reference a NumPy data array by column:
>>> D1[:,'col1']
      DataArray([8, 5, 0, 7, 8, 9, 9, 4])
      ('rows',)

撰写回答