创建2D数据的3D直方图

将二维数据的直方图演示为3D中的条形图。

创建2D数据的3D直方图示例

  1. # This import registers the 3D projection, but is otherwise unused.
  2. from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5. # Fixing random state for reproducibility
  6. np.random.seed(19680801)
  7. fig = plt.figure()
  8. ax = fig.add_subplot(111, projection='3d')
  9. x, y = np.random.rand(2, 100) * 4
  10. hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]])
  11. # Construct arrays for the anchor positions of the 16 bars.
  12. xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25, indexing="ij")
  13. xpos = xpos.ravel()
  14. ypos = ypos.ravel()
  15. zpos = 0
  16. # Construct arrays with the dimensions for the 16 bars.
  17. dx = dy = 0.5 * np.ones_like(zpos)
  18. dz = hist.ravel()
  19. ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')
  20. plt.show()

下载这个示例