Python描画3Dヒストグラム、3Dヒストグラムax.bar3d



Python Drawing 3d Histogram



三次元データに基づいて、ヒストグラムを描きます

インターネット上の多くのコードは少しあいまいであり、Baiduは使いやすいものではありません。一人でやってみるしかない。



import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Drawing settings fig = plt.figure() ax = fig.gca(projection='3d') # three-dimensional axis # The number of X and Y must be the same X = [1,2,3,4] Y = [5,6,7,8] Z = np.random.randint(0, 1000, 16) # Generate 16 random integers # meshgrid turns X and Y into a square length. For example, they are both 4. After meshgrid and ravel, the length becomes 16, because the grid points are 16 xx, yy = np.meshgrid(X, Y) # grid coordinate X, Y = xx.ravel(), yy.ravel() # Matrix flattening # Set column properties height = np.zeros_like(Z) # Create a new array of all 0s, with the same shape as Z, which is said to be the bottom position in the figure width = depth = 0.3 # The length and width of the column # Color array, the length is the same as Z c = ['r']*len(Z) # Start drawing, note that the original order is X, Y, Z, width, depth, height, but that will result in the formation of pillars, only the top of the pillar is thin, so Z and height must be interchanged ax.bar3d(X, Y, height, width, depth, Z, color=c, shade=False) # width, depth, height ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show()

効果:



一般的なエラー:ValueError:形状の不一致:オブジェクトを単一の形状にブロードキャストできません

理由:X、Y、Zの数が正しくありません。 Xの数とYの数は等しくなければならず(たとえば、両方ともN)、Zの数はN ^ 2です。

解決策:X、Y、Z配列の長さを調整します