如何在python中渲染3D直方图?

时间:2012-12-27 20:43:32

标签: python matplotlib plot data-visualization mayavi

我想从Hacker's Delight创建这样的情节:

enter image description here

在Python中有哪些方法可以实现这一目标?一种易于交互式调整图形(改变当前观察到的X / Y切片)的解决方案将是理想的。

matplotlib和mplot3d模块都没有此功能AFAICT。我发现mayavi2但它非常笨重(我甚至找不到调整大小的选项)并且从ipython运行时似乎只能正常工作。

或者gnuplot可以工作,但我不得不为此学习另一种语言语法。

1 个答案:

答案 0 :(得分:26)

由于TJD指出的例子似乎“难以理解”,这里是一个修改后的版本,其中有一些评论可能有助于澄清事情:

#! /usr/bin/env python
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
#
# Assuming you have "2D" dataset like the following that you need
# to plot.
#
data_2d = [ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
            [11, 12, 13, 14, 15, 16, 17, 18 , 19, 20],
            [16, 17, 18, 19, 20, 21, 22, 23, 24, 25],
            [21, 22, 23, 24, 25, 26, 27, 28, 29, 30] ]
#
# Convert it into an numpy array.
#
data_array = np.array(data_2d)
#
# Create a figure for plotting the data as a 3D histogram.
#
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
#
# Create an X-Y mesh of the same dimension as the 2D data. You can
# think of this as the floor of the plot.
#
x_data, y_data = np.meshgrid( np.arange(data_array.shape[1]),
                              np.arange(data_array.shape[0]) )
#
# Flatten out the arrays so that they may be passed to "ax.bar3d".
# Basically, ax.bar3d expects three one-dimensional arrays:
# x_data, y_data, z_data. The following call boils down to picking
# one entry from each array and plotting a bar to from
# (x_data[i], y_data[i], 0) to (x_data[i], y_data[i], z_data[i]).
#
x_data = x_data.flatten()
y_data = y_data.flatten()
z_data = data_array.flatten()
ax.bar3d( x_data,
          y_data,
          np.zeros(len(z_data)),
          1, 1, z_data )
#
# Finally, display the plot.
#
plt.show()