lawrence721
lawrence721

Reputation: 23

Plot 2D Histogram as heat map in matplotlib

I have 3-d data that I want to plot as the following histogram here. 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

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).

Upvotes: 2

Views: 2964

Answers (1)

HYRY
HYRY

Reputation: 97271

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)

here is the output:

enter image description here

Upvotes: 2

Related Questions