在matplotlib中绘制2D直方图作为热图

在matplotlib中绘制2D直方图作为热图

问题描述:

我有想要绘制为以下直方图的3-d数据. 对于每个垃圾箱,我都有一个带有两列的文本文件,例如

I have 3-d data that I want to plot as the following histogram . For each bin I have a text file with two columns such as

1.12    0.65
1.41    0.95
1.78    1.04
2.24    2.12

等第一列的第一个条目(在.txt中)为我提供了第一个图块的中心的值,第一列的第二行为我提供了第二个图块的中心的值,依此类推.第二列是指颜色栏上的值.第一列中的值以及仓位大小以对数间隔.我想在matplotlib中将其绘制得尽可能靠近上面(忽略箭头).

etc. The first entry of the first column (in the .txt) gives me the value for the center of the first tile, the second row of the first column gives me the value for the center of the second tile etc. The second column refers to the value on the color bar. The values in the first column and also the bin sizes are logarithmically spaced. I would like to plot this in matplotlib as close to the above as possible (ignoring the arrows).

我建议您使用PolyCollection:

I suggest you use 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)

这是输出: