在Python 3D图中使用Hist函数构建一维直方图系列
我正在使用Python的hist函数来生成与特定实验相关的1维直方图。现在我明白了,hist函数可以让我们在同一个x轴上绘制多个直方图,以便进行比较。通常我会使用类似下面的代码来实现这个目的,结果是一个非常不错的图表,其中x1、x2和x3的定义如下:
P.figure()
n, bins, patches = P.hist( [x0,x1,x2], 10, weights=[w0, w1, w2], histtype='bar')
P.show()
我希望能尝试实现一个3D效果,因此我想问一下,是否可以让每个独特的直方图在y轴上相互错开一定的单位,从而产生3D效果。
如果有人能帮忙,我将非常感激。
1 个回答
5
我觉得你想要的是 matplotlib.pyplot.bar3d
这个功能。
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x0, x1, x2 = [np.random.normal(loc=loc, size=100) for loc in [1, 2, 3]]
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
yspacing = 1
for i, measurement in enumerate([x0, x1, x2]):
hist, bin_edges = np.histogram(measurement, bins=10)
dx = np.diff(bin_edges)
dy = np.ones_like(hist)
y = i * (1 + yspacing) * np.ones_like(hist)
z = np.zeros_like(hist)
ax.bar3d(bin_edges[:-1], y, z, dx, dy, hist, color='b',
zsort='average', alpha=0.5)
plt.show()