如何使用python中内置函数的numpy或matplotlib正确生成3d直方图? [英] How to correctly generate a 3d histogram using numpy or matplotlib built in functions in python?

查看:28
本文介绍了如何使用python中内置函数的numpy或matplotlib正确生成3d直方图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这更多是关于在 python 中创建 3d 直方图的一般问题.

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

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

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

但是,我收到以下错误

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:Python27libsite-packagesmatplotlibaxes.py", line 7668, in hist
    m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
  File "C:Python27libsite-packages
umpylibfunction_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))我是否缺少步骤或参数?任何建议将不胜感激.

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.

推荐答案

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

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.

注意:结果将有很大差异,具体取决于您拥有的数据量以及您为直方图选择的 bin 数量.相应调整!

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

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

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.

这篇关于如何使用python中内置函数的numpy或matplotlib正确生成3d直方图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆