matplotlib:绘制n作为值的numpy数组

时间:2013-10-29 14:35:22

标签: python arrays numpy matplotlib nonetype

我有一个看起来像这样的数组:

k = numpy.array([(1.,0.001), (1.1, 0.002), (None, None), 
                 (1.2, 0.003), (0.99, 0.004)])

我想绘制不是(None, None)的值并保留数组值的索引。也就是说,只要有(None, None)值,我就想要一个间隙。

完成后我想绘制

y = k[:,0] + k[:,1]

但我甚至无法将数组添加到一起。我尝试屏蔽数组,但是我丢失了原始k数组的索引值。

一个最小的例子:

import matplotlib.pyplot as pyplot
import numpy

x = range(5)
k = numpy.array([(1.,0.001), (1.1, 0.002), (None, None), 
                 (1.2, 0.003), (0.99, 0.004)])

Fig, ax = pyplot.subplots()

# This plots a gap---as desired
ax.plot(x, k[:,0], 'k-')

# I'd like to plot
#     k[:,0] + k[:,1]
# but I can't add None

# Here I get rid of the (None, None) values so I can add
# But I lose the original indexing
mask = k != (None, None)
y = k[mask].reshape((-1,2))

ax.plot(range(len(y)), y[:,0]+y[:,1], 'k--')

2 个答案:

答案 0 :(得分:5)

您可以使用numpy.nan而不是None。

import matplotlib.pyplot as pyplot
import numpy

x = range(5)
k = numpy.array([(1.,0.001), (1.1, 0.002), (numpy.nan, numpy.nan), 
                 (1.2, 0.003), (0.99, 0.004)])

Fig, ax = pyplot.subplots()

# This plots a gap---as desired
ax.plot(x, k[:,0], 'k-')

ax.plot(range(len(y)), y[:,0]+y[:,1], 'k--')

或者您也可以屏蔽x值,因此x和y之间的索引是一致的

import matplotlib.pyplot as pyplot
import numpy

x = range(5)
y = numpy.array([(1.,0.001), (1.1, 0.002), (numpy.nan, numpy.nan), 
                 (1.2, 0.003), (0.99, 0.004)])

Fig, ax = pyplot.subplots()


ax.plot(range(len(y)), y[:,0]+y[:,1], 'k--')
import matplotlib.pyplot as pyplot
import numpy

x = range(5)
k = numpy.array([(1.,0.001), (1.1, 0.002), (None, None), 
                 (1.2, 0.003), (0.99, 0.004)])

Fig, ax = pyplot.subplots()

# This plots a gap---as desired
ax.plot(x, k[:,0], 'k-')

# I'd like to plot
#     k[:,0] + k[:,1]
# but I can't add None

arr_none = np.array([None])
mask = (k[:,0] == arr_none) | (k[:,1] == arr_none)

ax.plot(numpy.arange(len(y))[mask], k[mask,0]+k[mask,1], 'k--')

答案 1 :(得分:1)

您可以过滤阵列:

test = np.array([None])
k = k[k!=test].reshape(-1, 2).astype(float)

然后总结列并制作情节。您的方法的问题是您没有将None类型转换为numpy数组,这不允许正确创建掩码。