# Making 1D histogram out of 2D data using gnuplot?

I have data of the form:

``````x1 y1
x2 y2
...
``````

where each cuople `x, y` represents a point in the 2D plane.

I need a histogram of the point spread in the y-direction (eg. bin all points with similar y-value). This would be a projection on the y-axis, that is then turned into a histogram.

-
So what you want is: how many points have the y-value equals to `y` for each `y` in the data set? – cYrus Mar 24 '12 at 15:02
now just a histogram of the y values. – romeovs Mar 24 '12 at 15:18

There is no straightforward way to make an actual histogram, as this is not simply a plotting task but requires that the data be first sorted and binned. You can do that outside of gnuplot and plot the result from gnuplot simply with `plot 'file' with histo`.

Nevertheless, there are two main ways to do what you want entirely within gnuplot.

This first is an old trick that forces gnuplot to bin and sort the data for you using a little math and the `smooth freq` style. If your datafile is called "data" you can do:

``````w = 5
bin(x,wth) = width*floor(x/wth)
plot 'data' using (bin(\$2,bw)):(1.0) smooth freq with boxes
``````

This works but has all the disadvantages of histograms, mainly that the appearance of your distribution will depend on your chosen bin width, which you can assign to "w" in the first line.

Recent (> = 4.4) releases of gnuplot can calculate a kernel density estimate, which is like a bin-independent histogram: it gives you a continuous distribution. Also, it does the binning and sorting for you! You just need to say

``````plot 'data' using 2:(.001) smooth kden
``````

The .001 above will give you a normalized distribution if you have 1000 data points. You will want to substitute the reciprocal of the number of data points you have (or don't bother if you don't care whether your result is normalized).