How to correctly generate a 3d histogram using numpy or matplotlib built in functions in python?

后端 未结 4 542
难免孤独
难免孤独 2020-12-19 12:05

This is more of a general question about 3d histogram creation in python.

I have attempted to create a 3d histogram using the X and Y arrays in the following code

4条回答
  •  爱一瞬间的悲伤
    2020-12-19 12:39

    I've added to @lxop's answer to allow for arbitrary size buckets:

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt
    import numpy as np
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    
    x = np.array([0, 2, 5, 10, 2, 3, 5, 2, 8, 10, 11])
    y = np.array([0, 2, 5, 10, 6, 4, 2, 2, 5, 10, 11])
    # This example actually counts the number of unique elements.
    binsOne = sorted(set(x))
    binsTwo = sorted(set(y))
    # Just change binsOne and binsTwo to lists.
    hist, xedges, yedges = np.histogram2d(x, y, bins=[binsOne, binsTwo])
    
    # The start of each bucket.
    xpos, ypos = np.meshgrid(xedges[:-1], yedges[:-1])
    
    xpos = xpos.flatten()
    ypos = ypos.flatten()
    zpos = np.zeros_like(xpos)
    
    # The width of each bucket.
    dx, dy = np.meshgrid(xedges[1:] - xedges[:-1], yedges[1:] - yedges[:-1])
    
    dx = dx.flatten()
    dy = dy.flatten()
    dz = hist.flatten()
    
    ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')
    

提交回复
热议问题