如何正确生成 3d 直方图

发布于 2024-12-20 18:56:02 字数 1383 浏览 4 评论 0 原文

这更多是关于 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], bin=10, 范围=[[0, 10], [0, 10]]) 我也尝试过 numpy 的功能但没有成功 H, xedges, yedges = np.histogram2d(x, y, bins = (10, 10)) 我是否缺少步骤或参数?任何建议将不胜感激。

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

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

However, I am getting the following error

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

I have tried the code with and without the "[" in the line
ax.hist([X, Y], bins=10, range=[[0, 10], [0, 10]])
I have also tried the function from numpy without success
H, xedges, yedges = np.histogram2d(x, y, bins = (10, 10))
Am I missing a step or a parameter? Any advice would be greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

櫻之舞 2024-12-27 18:56:02

我将其发布在有关彩色 3D 条形图的相关线程中,但我认为它也与此相关,因为我无法在任一线程中找到我需要的完整答案。此代码为任何类型的 xy 数据生成直方图散点图。高度表示该箱中值的频率。因此,例如,如果您有许多 (x,y) = (20,20) 的数据点,那么它会很高且呈红色。如果箱中 (x,y) = (100,100) 的数据点很少,那么它会是低的和蓝色的。

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

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 数据点的结果。请注意,您可以拖放到不同的视角,并且可能希望保存多个视图以供演示和后代使用。

3d 直方图侧面查看></a><br />
<a href=3d 直方图透视图2

I posted this in a related thread about colored 3d bar plots, but I think it's also relevant here as I couldn't find a complete answer for what I needed in either thread. This code generates a histogram scatterplot for any sort of x-y data. The height represents the frequency of values in that bin. So, for example, if you had many data point where (x,y) = (20,20) it would be high and red. If you had few data points in the bin where (x,y) = (100,100) it would be low and blue.

Note: result will vary substantially depending on how much data you have and how many bins your choose for you histogram. Adjust accordingly!

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

The results for about 75k data points of mine are below. Note, you can drag and drop to different perspectives and may want to save multiple views for presentations, posterity.

3d histogram side view
3d histogram perspective 2

情绪 2024-12-27 18:56:02

看看
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 () 来做到这一点。

Have a look at
https://matplotlib.org/stable/gallery/mplot3d/hist3d.html, this has a working example script.

I've improved the code at that link to be more of a histogram:

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

I'm not sure how to do it with Axes3D.hist ().

林空鹿饮溪 2024-12-27 18:56:02

在此答案中有一个针对散点的 2D 和 3D 直方图的解决方案。用法很简单:

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

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

其中 sub 是一个 matplotlib "Subplot" 实例(3D 或非 3D),并且 points 包含用于散点图的点。

In this answer there is a solution for 2D and 3D Histograms of scattered points. The usage is simple:

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

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

Where sub is a matplotlib "Subplot" instance (3D or not) and pointscontains the points used for the scatter plot.

浮光之海 2024-12-27 18:56:02

我已添加到 @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')

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')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文