A fork of the code from @ejb 's block for his blog post “A better way to structure D3 code”.
Code for the histogram itself was heavily borrowed from this bl.ock by Mike Bostock.
Takes data in the form of a vector of numerical values.
Also see my second visualization using @ejb's style: the dotplot.
This is part of my larger project of making a d3/r library for dynamic and interactive basic statistical plots.
forked from nstrayer's block: Reusable D3 Histograms
xxxxxxxxxx
<!-- load in D3 and Chart constructor scripts -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script src="chart.js"></script>
<style>
/* a little bit of CSS to make the chart readable */
.axis path, .tick line {
fill: none;
stroke: #333;
}
</style>
<!-- here's the div our chart will be injected into -->
<div class="chart-container" style="max-width: 1000px;"></div>
<!-- these will be made useful in the script below -->
<button class="color" data-color="red">red bars</button>
<button class="color" data-color="green">green bars</button>
<button class="color" data-color="blue">blue bars</button>
<button class="data">change data</button>
<script>
// create new chart using Chart constructor
var chart = new Chart({
element: document.querySelector('.chart-container'),
data: d3.range(1000).map(d3.random.normal()),
bins: 20
});
// change line colour on click
d3.selectAll('button.color').on('click', function(){
var color = d3.select(this).text().split(' ')[0];
chart.setColor( color );
});
// change data on click to something randomly-generated
d3.selectAll('button.data').on('click', function(){
chart.setData(d3.range(1000).map(function(){return Math.random() * 50}));
});
// redraw chart on each resize
// in a real-world example, it might be worth ‘throttling’ this
// more info: https://sampsonblog.com/749/simple-throttle-function
d3.select(window).on('resize', function(){
chart.draw();
});
</script>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js