|
<!-- load in D3 and Chart constructor scripts --> |
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script> |
|
<script src="chart.js"></script> |
|
|
|
<style> |
|
/* a little bit of CSS to make the chart readable */ |
|
.line { |
|
fill: none; |
|
stroke-width: 4px; |
|
} |
|
.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 line</button> |
|
<button class="color" data-color="green">green line</button> |
|
<button class="color" data-color="blue">blue line</button> |
|
<button class="data">change data</button> |
|
|
|
<script> |
|
// create new chart using Chart constructor |
|
const chart = new Chart({ |
|
element: document.querySelector('.chart-container'), |
|
data: [ |
|
[new Date(2016,0,1), 10], |
|
[new Date(2016,1,1), 70], |
|
[new Date(2016,2,1), 30], |
|
[new Date(2016,3,1), 10], |
|
[new Date(2016,4,1), 40] |
|
] |
|
}); |
|
// change line colour on click |
|
d3.selectAll('button.color').on('click', function(){ |
|
const color = d3.select(this).text().split(' ')[0]; |
|
chart.setColor( color ); |
|
}); |
|
// change data on click to something randomly-generated |
|
d3.selectAll('button.data').on('click', () => { |
|
chart.setData([ |
|
[new Date(2016,0,1), Math.random()*100], |
|
[new Date(2016,1,1), Math.random()*100], |
|
[new Date(2016,2,1), Math.random()*100], |
|
[new Date(2016,3,1), Math.random()*100], |
|
[new Date(2016,4,1), Math.random()*100] |
|
]); |
|
}); |
|
// redraw chart on each resize |
|
// in a real-world example, it might be worth ‘throttling’ this |
|
// more info: http://sampsonblog.com/749/simple-throttle-function |
|
d3.select(window).on('resize', () => chart.draw() ); |
|
</script> |
Hey! Thanks for the example!
It'd be better to the
General Update Patterns
here.https://bl.ocks.org/mbostock/3808218
https://bl.ocks.org/mbostock/3808221
https://bl.ocks.org/mbostock/3808234