gpt4 book ai didi

python - matplotlib:以 None 作为值绘制 numpy 数组

转载 作者:太空狗 更新时间:2023-10-29 22:30:47 25 4
gpt4 key购买 nike

我有一个数组,如下所示:

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--')

最佳答案

您可以使用 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--')

关于python - matplotlib:以 None 作为值绘制 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19661198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com