首页 > 解决方案 > 如何过滤数组中不需要的值以进行绘图?使用 numpy 数组的 matplotlib 中的 ValueError

问题描述

我正在一些基于 OOP 的代码中编写一个新例程,并且在修改数据数组时遇到了问题(代码的简短示例如下)。

基本上,这个例程是取数组R,转置然后排序,然后过滤掉低于预定值thres的数据。然后,我将这个数组重新转置回它的原始维度,然后用T的第一个元素绘制它的每一行。

import numpy as np
import matplotlib.pyplot as plt

R = np.random.rand(3,8)
R = R.transpose() # transpose the random matrix
R = R[R[:,0].argsort()] # sort this matrix
print(R)

T = ([i for i in np.arange(1,9,1.0)],"temps (min)")

thres = float(input("Define the threshold of coherence: "))

if thres >= 0.0 and thres <= 1.0 :
        R = R[R[:, 0] >= thres] # how to filter unwanted values? changing to NaN / zeros ?
else :
        print("The coherence value is absurd or you're not giving a number!")

print("The final results are ")
print(R)
print(R.transpose())
R.transpose() # re-transpose this matrix

ax = plt.subplot2grid( (4,1),(0,0) )
ax.plot(T[0],R[0])
ax.set_ylabel('Coherence')

ax = plt.subplot2grid( (4,1),(1,0) )
ax.plot(T[0],R[1],'.')
ax.set_ylabel('Back-azimuth')

ax = plt.subplot2grid( (4,1),(2,0) )
ax.plot(T[0],R[2],'.')
ax.set_ylabel('Velocity\nkm/s')
ax.set_xlabel('Time (min)')

但是,我遇到一个错误

ValueError: x and y must have same first dimension, but have shapes (8,) and (3,)

我评论了我认为问题可能存在的部分(如何过滤不需要的值?),但问题仍然存在。

如何绘制这两个数组(RT),同时仍然能够过滤掉低于thres的不需要的值?我可以将这些不需要的值转换为零或 NaN,然后​​成功绘制它们吗?如果是,我该怎么做?

您的帮助将不胜感激。

标签: python-3.xmatplotlibnumpy-ndarrayvalueerror

解决方案


在技​​术朋友的帮助下,保留这部分简单地解决了问题

R = R[R[:, 0] >= thres]

因为删除不需要的元素比将它们更改为 NaN 或零更可取。然后通过在这部分添加轻微修改来解决绘图问题

ax.plot(T[0][:len(R[0])],R[0])

以及随后的绘图部分。这将T切成与R相同的维度。


推荐阅读