Skip to content

Instantly share code, notes, and snippets.

@RyanAtViceSoftware
Last active October 22, 2017 18:16
Show Gist options
  • Save RyanAtViceSoftware/edf067a406db03e1664d3d6191336d9d to your computer and use it in GitHub Desktop.
Save RyanAtViceSoftware/edf067a406db03e1664d3d6191336d9d to your computer and use it in GitHub Desktop.
D3 Example

Running the Sample

To view this in a JS fiddle use the url below:

http://jsfiddle.net/gh/gist/library/pure/edf067a406db03e1664d3d6191336d9d/

What it does

The bars will change colors when you mouse over and clicking on the bars will show the associated data element in an alert box.

Demo

Troubleshooting

I tried to configure the manifest to use Babel but I'm not sure that it worked and there's a latency from when you make changes to when you see them in the JsFiddles so please make sure that JS is set to Babel as shown below or it won't work.

Set JS to Babel

.chart {
background-color: lightgray;
width: 200px;
height: 300px;
border: 1px solid black;
}
.bar {
height: 30px;
fill: lightgreen;
stroke: black;
stroke-width: 1;
}
.barOn {
fill: lightblue
}
<div class="chart"></div>
const scores = [
{ name: 'Alice', score: 93},
{ name: 'Jack', score: 86},
{ name: 'Frank', score: 90},
{ name: 'Sam', score: 82},
{ name: 'Jane', score: 97}
];
const bar = d3.select('.chart')
.append('svg')
.attr('width', 225)
.attr('height', 300)
.selectAll('g')
.data(scores)
.enter()
.append('g')
.attr(
'transform',
(d, i) => 'translate(0,' + i*33 + ')'
);
const rect = bar.append('rect')
.attr('class', 'bar')
.on('click', function(d) { alert(JSON.stringify(d)); })
.style('width', d => d.score);
rect.on('mouseover', function() {
// It would be more appropriate to do this as pure css .bar:hover
// but I'm just exploring D3 here
d3.select(this)
.classed('barOn', true);
})
.on('mouseout', function() {
// It would be more appropriate to do this as pure css .bar:hover
// but I'm just exploring D3 here
d3.select(this)
.classed('barOn', false);
})
bar.append('text')
.text(d => d.name)
.attr('y', 20);
name: D3 V4 Example
authors:
- Ryan Vice
resources:
- https://d3js.org/d3.v4.min.js
normalize_css: no
wrap: b
panel_js: 3
panel_css: 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment