Plot 2D Histogram as heat map in matplotlib

我与影子孤独终老i 提交于 2019-12-11 00:36:00

问题


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

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


回答1:


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:



来源:https://stackoverflow.com/questions/21837713/plot-2d-histogram-as-heat-map-in-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!