1

I have a specification of bin shapes and positions on the form [a,b] whith a and b two numpy array of size 2 (for the dimensions).

I also have, for each bin, the frequency of data in the bin. The specification can look like that :

import numpy as np
bins = np.array([[[0,0],[1/2,1/2]],[[1/2,0],[1,1/2]],[[0,1/2],[1/2,1]],[[1/2,1/2],[4/5,4/5]],[[4/5,1/2],[1,4/5]],[[1/2,4/5],[4/5,1]],[[4/5,4/5],[1,1]]])
weights = [10,20,5,35,10,15,5]

How can i plot a histogram looking like this one https://stackoverflow.com/a/52403355/8425270 but with thoose bins ? Or just similar to the output of sns.heatmap (i.e in 2 dimensions) but with the specified un-regular grid.

lrnv
  • 1,038
  • 8
  • 19

1 Answers1

1

I'm not sure about your x-y convention, but this should do the job for you:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm

fig = plt.figure(figsize=(6, 5))
ax1 = fig.add_subplot(111, projection='3d')

bins = np.array([[[0,0],[1/2,1/2]],[[1/2,0],[1,1/2]],[[0,1/2],[1/2,1]],[[1/2,1/2],[4/5,4/5]],[[4/5,1/2],[1,4/5]],[[1/2,4/5],[4/5,1]],[[4/5,4/5],[1,1]]])
weights = np.array([10,20,5,35,10,15,5])
x = bins[:,0,0]
dx = bins[:,1,0]
y = bins[:,0,1]
dy = bins[:,1,1]

bottom = np.zeros_like(weights)

cmap = cm.get_cmap('viridis')
rgba = [cmap((k-np.min(weights))/np.max(weights)) for k in weights] 
ax1.bar3d(x, y, bottom, dx, dy, weights, shade=True, zsort='max', color=rgba)
plt.show()

enter image description here

Andrea
  • 2,932
  • 11
  • 23
  • This. Is. Just. What. I. Wanted. Stunning. Thanks a lot. Indeed you were right the x/y convention you took is not the one i meant but substracting x/y to your dx and dy i get exactly the plot i want. Thanks a lot for sharing the knowledge. – lrnv Nov 28 '19 at 13:02
  • Just one more thing : What if i want to have a 2D version of this heatmap ? To be able to plot several side by side for higher-dimensional data – lrnv Nov 28 '19 at 13:34
  • Glad to help. For the 2D version, I would go for simple [rectangles](https://matplotlib.org/3.1.1/gallery/statistics/errorbars_and_boxes.html#sphx-glr-gallery-statistics-errorbars-and-boxes-py), setting the color using the same method of the example above. Not sure I understood the question though – Andrea Nov 28 '19 at 13:49
  • Yes you did. My question is exactly the same graph but flat. Thanks for the head's up on rectangles – lrnv Nov 28 '19 at 14:20