# Counting the number of elements in bin

I have a 2D dataset (x,y) for which the X coordinate range is -4000-7000 and the y range is 1000-9000. The data needs to be created.

I would like to divide the x-y plane into several bins and count the number of elements in each bin. How can I do it? I use the Bincounts but it does not give me the correct answer.

BinCounts[data, {Xmin, Xmax, xbinsz}, {ymin, ymax, ybinsz}]


Clear["Global*"]

SeedRandom[1234];

data = RandomReal[{-4000, 9000}, {1000, 2}];

xmin = Floor@Min@data[[All, 1]];

xmax = Ceiling@Max@data[[All, 1]];

xbinsz = (xmax - xmin)/10;

ymin = Floor@Min@data[[All, 2]];

ymax = Ceiling@Max@data[[All, 2]];

ybinsz = (ymax - ymin)/10;

bc = BinCounts[data, {xmin, xmax, xbinsz}, {ymin, ymax, ybinsz}]

(* {{7, 10, 7, 7, 6, 12, 11, 16, 8, 10}, {15, 6, 14, 6, 9, 5, 13, 11, 9, 9}, {5,
15, 12, 5, 9, 11, 16, 9, 7, 8}, {8, 8, 11, 10, 11, 7, 8, 8, 12, 9}, {8, 8,
11, 5, 11, 10, 10, 8, 11, 9}, {15, 5, 16, 8, 10, 3, 7, 13, 16, 10}, {17, 12,
6, 11, 13, 9, 11, 17, 15, 6}, {5, 5, 6, 11, 8, 11, 10, 9, 10, 10}, {9, 17,
11, 10, 13, 11, 6, 7, 10, 13}, {12, 9, 13, 13, 16, 12, 4, 14, 13, 11}} *)


All of the data is included

Length[data] == Total[Flatten@bc]

(* True *)

{nrow, ncol} = Dimensions@bc

(* {10, 10} *)

DiscretePlot3D[bc[[row, col]], {row, 1, nrow}, {col, 1, ncol},
ExtentSize -> 0.75]


Uniformly distributed data:

data = RandomVariate[
UniformDistribution[{{-4000, 7000}, {1000, 9000}}], 1000];


To generate the blue rectangle bins (1000 x 1000):

t = Table[
Rectangle[{i, j}, {i + 1000, j + 1000}], {i, -4000, 6000,
1000}, {j, 1000, 8000, 1000}];


Plotting: (change opacity to 0.1 to see y-axis)

ListPlot[data
, PlotStyle -> {Black, AbsolutePointSize[2]}
, PlotRange -> Full
, AspectRatio -> Automatic
, Epilog -> {EdgeForm[Red], FaceForm[White], Opacity[0.5],
Rectangle[{-4050, 950}, {7050, 9050}]
, EdgeForm[Blue], t
}
]


Counting and ArrayPlot visualization:

cts = BinCounts[data, {-4000, 7000, 1000}, {1000, 9000, 1000}];
ArrayPlot[cts
, Frame -> True
, FrameTicks -> Automatic
, AspectRatio -> Automatic
]


cts
`

{{11,8,5,9,16,6,17,9},{16,16,7,7,13,9,10,10},{8,15,16,6,14,10,13,14},{12,9,8,10,15,11,17,9},{8,8,11,12,14,7,9,8},{13,19,10,12,10,14,7,9},{9,11,13,7,12,11,17,8},{12,12,10,7,10,10,14,12},{13,12,13,11,11,13,15,16},{12,11,16,12,8,12,14,10},{11,20,10,10,9,14,15,10}}