Smooth/histogram a 2D set
Let's start with your sample data:
In[1]:= data = {{0.1, 1.0}, {0.2, 2.0}, {0.3, 3.0}, {0.35, 3.5}, {0.4, 4.0}, {0.5, 5.0}};
First we can use GatherBy
to group entries by bin:
In[2]:= GatherBy[data, Ceiling[First[#], 0.2] &]
Out[2]= {{{0.1, 1.}, {0.2, 2.}}, {{0.3, 3.}, {0.35, 3.5}, {0.4, 4.}}, {{0.5, 5.}}}
Then select the second element of each pair (Last
) and calculate the means:
In[3]:= Mean[Last /@ #] & /@ %
Out[3]= {1.5, 3.5, 5.}
I propose:
data = {{0.1, 1.0}, {0.2, 2.0}, {0.3, 3.0}, {0.35, 3.5}, {0.4, 4.0}, {0.5, 5.0}};
Mean /@ Reap[#2 ~Sow~ Ceiling[#, 0.2] & @@@ data][[2]]
{1.5, 3.5, 5.}
Another offering making use of BinLists
:
data = {{0.1, 1.0}, {0.2, 2.0}, {0.3, 3.0}, {0.35, 3.5}, {0.4,
4.0}, {0.5, 5.0}};
Smoothed[data_, binSize_] :=
With[{xs = data\[Transpose] // First, ys = data\[Transpose] // Last},
Mean@ys[[#]] & /@ (Flatten[Map[Position[xs, #] &, #]] & /@
BinLists[xs, 0.2 + $MachineEpsilon])]
Smoothed[data, 0.2]
(* -> {1.5, 3.5, 5.} *)