绘制来自大型稀疏numpy.ndarray的数据,在3D条形图中使用不同的数组长度

时间:2017-04-20 03:37:33

标签: python matplotlib plot

我的问题类似于question,我想将光谱数据绘制成3D图,但

1)我的数据是np.ndarray中的矩阵

2)它的大尺寸为1201 * 5001(result.shape = (1201,5001)),因此手动硬编码标签不合适。

3)数据不连续且稀疏。最终的情节可能看起来像mplot3d bar3d。

在这种情况下,我可以使用Matplotlib的3D条形图吗?如果可能,如何为每个轴定义不同的长度?

这是我正在进行的代码(第3次更新)

if __name__ == '__main__':
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib
%matplotlib inline

# from array, x is time, y is mz, z is intensity
# in graph x is mz, y is time, z is intensity

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

zs = np.arange(0, 50.01, 0.01)

    for z in zs:
        xs = np.arange(300, 1500.01, 1)
        ys = result

        ax.bar(xs,ys,zs=z,zdir='y')

plt.show()

错误(第3次)

Traceback (most recent call last):
  File "prelimnmf_importcsv3.py", line 70, in <module>
    ax.bar(xs,ys,zs=z,zdir='y')
  File "/Users/pp/anaconda/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 2394, in bar
    patches = Axes.bar(self, left, height, *args, **kwargs)
  File "/Users/pp/anaconda/lib/python2.7/site-packages/matplotlib/__init__.py", line 1892, in inner
    return func(ax, *args, **kwargs)
  File "/Users/pp/anaconda/lib/python2.7/site-packages/matplotlib/axes/_axes.py", line 2115, in bar
    if h < 0:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

1 个答案:

答案 0 :(得分:1)

虽然我怀疑1200 * 5000的条形图可以提供对数据的任何视觉洞察,但仍然可以使用它。

所以这是一个例子

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

#Assume you have arrays like this
x = np.arange(300,1500,100)
y = np.arange(4)*10
Z = np.random.rand(len(y), len(x))*33

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

for i in range(len(y))[::-1]:
    c = plt.cm.jet(i/float(len(y)))
    ax.bar(x, Z[i,:], zs=y[i], zdir='y',  width=80,alpha=1 )

ax.set_xlabel('time')
ax.set_ylabel('mz')
ax.set_zlabel('intensity')

plt.show()

enter image description here