Python绘制二维直方图

3 投票
2 回答
15338 浏览
提问于 2025-04-16 22:17

我正在尝试用这些代码在Python中绘制一个二维直方图

from math import *
import pylab as p
import matplotlib.pyplot as plt
import numpy as np

x=part.points[:,0]
y=part.points[:,1]
z=part.points[:,2]

H, xedges, yedges = np.histogram2d(x, y, bins=(128,128))
H.shape, xedges.shape, yedges.shape

extent = [yedges[0], yedges[-1], xedges[-1], xedges[0]]

plt.imshow(H, extent=extent, interpolation='nearest')

plt.colorbar()
plt.xlabel("x")
plt.ylabel("y")
plt.show()

一切都运行得很好:我有一个颜色条,表示每个单元格中的计数。不过,我想要的是计数的对数值,但histrogram2d这个函数没有这个选项。

2 个回答

3

在这个回答中,有一个关于二维和三维散点图以及气泡直方图的解决方案。

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

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

这里的 sub 是一个 matplotlib"子图" 实例,可以是三维的,也可以是二维的,而 points 则包含了用于散点图的点。

在这里输入图片描述

5

我想你可以简单地这样做:

H_log = np.log(H)
…
plt.imshow(H_log,…)

(假设你没有空值的情况)。

如果你想要一个3D的柱状图,你可以参考Matplotlib文档中提供的示例

更一般来说,我强烈建议你查看非常有用的Matplotlib图库,当你需要一些特定的绘图功能时,这里会有很多帮助。

撰写回答