kevinkayaks
kevinkayaks

Reputation: 2726

matplotlib 2d histrogram heatmap-- how do I use my dataset to make one?

I am new to python.
I have a dataset like

import numpy as np
from matplotlib import pyplot as plt     
dats = np.array([r1,x1,y1],[r2,x2,y2],...])

I would like to plot color intensity associated with r1,r2,... at the position (x1,y1), (x2,y2), et cetera respectively.

How can I get this data set manipulated in a format which matplotlib can use in a 2D histogram?
Any help much appreciated. I'll help others in return once I've gained some skill : o

Upvotes: 0

Views: 813

Answers (3)

alexblae
alexblae

Reputation: 746

I think what you are looking for is not a histogram but a contour plot (a histogram would count the number of occurrences of a coordinate (x,y) falling into a bin).

If your data is not on a grid, you can use tricontourf:

plt.tricontourf(dats[:,1],dats[:,2],dats[:,0],cmap='hot')
plt.colorbar()
plt.show()

There are more ways to plot this, such as scatter plots etc.

Upvotes: 0

MaxPowers
MaxPowers

Reputation: 5486

In order to make 2D histogram, your data set has to comprises two data values rather than one data value and two indices. Thus, you need two arrays: one containing the r1 values and one containing the r2 values. Your data does not have any r2 values, therefore, you cannot compute a bi-dimensional histogram.

Regarding your question, you do not even want a histogram. You just want to visualise your r1 values on a plane. This is easy. Say, your array dats has a length of 100, then:

rs = dats[:, 0]    # retrieve r-values from dats

plt.imshow(rs.reshape(10, 10), cmap='Greys', interpolation='None')
plt.colorbar()

Upvotes: 1

Ed Smith
Ed Smith

Reputation: 13206

You can create interpolated data from a set of points using griddata, assuming x = [x1, x2, etc] and r = [r1, r2, etc] then,

#Setup a grid
xi = np.linspace(x.min(),x,max(),100)
yi = np.linspace(y.min(),y.max(),100)
zi = griddata(x, y, r, xi, yi, interp='linear')

#Plot the colormap
cm = plt.pcolormesh(xi,yi,zi)
plt.colorbar()
plt.show()

Other options include colouring scatter plots,

plt.scatter(x,y,c=r)

or there is a 2D histogram functions in scipy where you could set the weights based on r,

H, xedges, yedges = np.histogram2d(x, y, w_i = r)

I haven't used the last one personally.

Upvotes: 0

Related Questions