将2D直方图绘制为matplotlib中的热图

时间:2014-02-17 19:30:04

标签: python matplotlib plot histogram

我想要将3-d数据绘制为以下直方图here。 对于每个bin,我有一个包含两列的文本文件,例如

1.12    0.65
1.41    0.95
1.78    1.04
2.24    2.12

等。第一列的第一个条目(在.txt中)给出了第一个瓷砖中心的值,第一个列的第二个行给出了第二个瓷砖中心的值等。第二个列是指颜色条上的值。第一列中的值以及箱尺寸以对数间隔。我想在matplotlib中绘制尽可能接近上面的内容(忽略箭头)。

1 个答案:

答案 0 :(得分:2)

我建议你使用PolyCollection:

import numpy as np
import pylab as pl
import matplotlib.collections as mc

x = np.logspace(1, 2, 20)
polys = []
values = []
for xs, xe in zip(x[:-1], x[1:]):
    y = np.logspace(1.0, 2+np.random.rand()+2*np.log10(xs), 30)
    c = -np.log(xs*y)
    yp = np.c_[y[:-1], y[:-1], y[1:], y[1:]]
    xp = np.repeat([[xs, xe, xe, xs]], len(yp), axis=0)
    points = np.dstack((xp, yp))
    polys.append(points)
    values.append(c[:-1])

polys = np.concatenate(polys, 0)
values = np.concatenate(values, 0)

pc = mc.PolyCollection(polys)
pc.set_array(values)
fig, ax = pl.subplots()
ax.add_collection(pc)
ax.set_yscale("log")
ax.set_xscale("log")
ax.autoscale()    
pl.colorbar(mappable=pc)

这是输出:

enter image description here

相关问题