【问题标题】:How to correctly generate a 3d histogram using numpy or matplotlib built in functions in python?如何使用 python 中内置的 numpy 或 matplotlib 函数正确生成 3d 直方图?
【发布时间】:2012-01-16 06:58:47
【问题描述】:

这是一个关于在 python 中创建 3d 直方图的一般性问题。

我尝试在以下代码中使用 X 和 Y 数组创建 3d 直方图

import matplotlib
import pylab
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib import cm

def threedhist():
    X = [1, 3, 5, 8, 6, 7, 1, 2, 4, 5]
    Y = [3, 4, 3, 6, 5, 3, 1, 2, 3, 8]
    fig = pylab.figure()
    ax = Axes3D(fig)
    ax.hist([X, Y], bins=10, range=[[0, 10], [0, 10]])
    plt.xlabel('X')
    plt.ylabel('Y')
    plt.zlabel('Frequency')
    plt.title('Histogram')
    plt.show()

但是,我收到以下错误

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    a3dhistogram()
  File "C:/Users/ckiser/Desktop/Projects/Tom/Python Files/threedhistogram.py", line 24, in a3dhistogram
    ax.hist([X, Y], bins=10, range=[[0, 10], [0, 10]])
  File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 7668, in hist
    m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
  File "C:\Python27\lib\site-packages\numpy\lib\function_base.py", line 169, in histogram
    mn, mx = [mi+0.0 for mi in range]
TypeError: can only concatenate list (not "float") to list

我已经尝试过在行中有和没有“[”的代码 ax.hist([X, Y], bins=10, range=[[0, 10], [0, 10]]) 我也尝试过 numpy 的功能但没有成功 H, xedges, yedges = np.histogram2d(x, y, bins = (10, 10)) 我是否缺少步骤或参数?任何建议将不胜感激。

【问题讨论】:

  • 你检查下面的答案了吗?

标签: python numpy matplotlib 3d histogram


【解决方案1】:

我在一个关于彩色 3d 条形图的相关线程中发布了这个,但我认为它在这里也很相关,因为我在任何一个线程中都找不到我需要的完整答案。此代码为任何类型的 x-y 数据生成直方图散点图。高度表示该 bin 中值的频率。因此,例如,如果您有许多 (x,y) = (20,20) 的数据点,它将是高且红色的。如果您在 (x,y) = (100,100) 的 bin 中只有很少的数据点,它将是低的和蓝色的。

注意:结果会根据您拥有的数据量以及您为直方图选择的 bin 数量而有很大差异。相应调整!

xAmplitudes = #your data here
yAmplitudes = #your other data here

x = np.array(xAmplitudes)   #turn x,y data into numpy arrays
y = np.array(yAmplitudes)

fig = plt.figure()          #create a canvas, tell matplotlib it's 3d
ax = fig.add_subplot(111, projection='3d')

#make histogram stuff - set bins - I choose 20x20 because I have a lot of data
hist, xedges, yedges = np.histogram2d(x, y, bins=(20,20))
xpos, ypos = np.meshgrid(xedges[:-1]+xedges[1:], yedges[:-1]+yedges[1:])

xpos = xpos.flatten()/2.
ypos = ypos.flatten()/2.
zpos = np.zeros_like (xpos)

dx = xedges [1] - xedges [0]
dy = yedges [1] - yedges [0]
dz = hist.flatten()

cmap = cm.get_cmap('jet') # Get desired colormap - you can change this!
max_height = np.max(dz)   # get range of colorbars so we can normalize
min_height = np.min(dz)
# scale each z to [0,1], and get their rgb values
rgba = [cmap((k-min_height)/max_height) for k in dz] 

ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=rgba, zsort='average')
plt.title("X vs. Y Amplitudes for ____ Data")
plt.xlabel("My X data source")
plt.ylabel("My Y data source")
plt.savefig("Your_title_goes_here")
plt.show()

我的大约 75k 个数据点的结果如下。请注意,您可以拖放到不同的视角,并且可能希望保存多个视图以供演示、后代使用。

【讨论】:

  • 不错的图,但是您的数据不是以零为中心...如果您采用奇数箱(尝试箱=(7,7)),那么当它应该是中心时,一个条从零开始归零。 @ArtifexR
  • 我已经解决了,但我觉得还不够强大,无法更正您的代码。你必须用 ' xpos, ypos = np.meshgrid(xedges[:-1]+xedges[1:], yedges[:-1]+yedges[1:]) xedges[:-1]+xedges[1:], yedges[:-1]+yedges[1:]) - abs(xedges[1]-xedges[0]) ' 你的偏移量将被纠正。跨度>
【解决方案2】:

看看 https://matplotlib.org/stable/gallery/mplot3d/hist3d.html,这有一个工作示例脚本。

我已经改进了该链接上的代码,使其更像是一个直方图:

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 = [1, 3, 5, 8, 6, 7, 1, 2, 4, 5]
y = [3, 4, 3, 6, 5, 3, 1, 2, 3, 8]

hist, xedges, yedges = np.histogram2d(x, y, bins=(4,4))
xpos, ypos = np.meshgrid(xedges[:-1]+xedges[1:], yedges[:-1]+yedges[1:])

xpos = xpos.flatten()/2.
ypos = ypos.flatten()/2.
zpos = np.zeros_like (xpos)

dx = xedges [1] - xedges [0]
dy = yedges [1] - yedges [0]
dz = hist.flatten()

ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')
plt.xlabel ("X")
plt.ylabel ("Y")

plt.show()

我不确定如何使用 Axes3D.hist () 来实现。

【讨论】:

    【解决方案3】:

    In this answer 有散点的 2D 和 3D 直方图的解决方案。用法很简单:

    points, sub = hist2d_scatter( radius, density, bins=4 )
    
    points, sub = hist3d_scatter( temperature, density, radius, bins=4 )
    

    其中submatplotlib "Subplot" 实例(3D 与否),points包含用于散点图的点。

    【讨论】:

      【解决方案4】:

      我已添加到@lxop 的答案以允许任意大小的存储桶:

      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')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-18
        • 2015-08-23
        • 1970-01-01
        • 2016-05-07
        • 2020-12-02
        • 2014-05-17
        • 1970-01-01
        • 2012-07-12
        相关资源
        最近更新 更多