How can I draw a one axis frequency distribution graph in d3? The plot should take an array like [3 34 234 32 33 23] and draw a marker at every of the occurring elements on a one dimensional axis. The graph should look like this:
There are ways to plot histograms like this in d3:
// Generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
.bins(x.ticks(20))
(values);
But how can I generate the one dimensional version of these?
Here are two possible approaches, depending on what you want:
Just draw a semitransparent rectangle for each data point. Example: http://bl.ocks.org/anonymous/be1b4d11d420bcfc76a6a2005d0b2fe5
var data = d3.layout.histogram().bins(x.ticks(20))(values);
just generates data, and not the chart. You can use that data to make a one-dimensional chart.
For example, if you're referring to Mike Bostock's example histogram at: http://bl.ocks.org/mbostock/3048450, you can remove the frequency mapping to bar height, and map it to opacity instead. First you'd add a scale that maps frequency to opacity:
var opacity = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d.y; })])
.range([0, 1]);
and change the line that says:
.attr("height", function(d) { return height - y(d.y); });
to something like:
.attr("height", 50)
.style("opacity", function(d) { return opacity(d.y); });
You'd also want to reformat the height and spacing of the bars. You can see a sample here: http://bl.ocks.org/anonymous/d460f85cc770a7c63221d390d733c1f5
Alternatively you may want to map frequency to color, instead of opacity, in that case your scale would be a color scale, and you'd use "fill" instead of "opacity".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With