【问题标题】:How can I render 3D histograms in python?如何在 python 中渲染 3D 直方图?
【发布时间】:2012-12-13 05:16:59
【问题描述】:

我想从Hacker's Delight 制作这样的情节:

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

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

另外,gnuplot 也可以工作,但我不想为此学习另一种语言语法。

【问题讨论】:

  • matplotlib 支持。看到这个:matplotlib.org/examples/mplot3d/hist3d_demo.html
  • @TJD:很好的发现。哎呀,这个例子看起来难以理解。
  • 你试过barchart().
  • 如果您解释了要绘制的数据的起始状态,可以提供更具体的答案。
  • @101100:开始(也是唯一)状态是一个二维整数数组。我不希望随着时间的推移制作动画或类似的东西。

标签: python matplotlib plot data-visualization mayavi


【解决方案1】:

由于 TJD 指出的示例似乎“难以理解”,因此这里是一个带有一些 cmets 的修改版本,可能有助于澄清事情:

#! /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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 2011-01-02
    • 2018-04-10
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 2021-02-01
    相关资源
    最近更新 更多