Built with blockbuilder.org
forked from Jverma's block: Scatterplot of Iris data : d3 v4
xxxxxxxxxx
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scatterplot d3v4</title>
<style type="text/css">
body{
margin: 0;
font-family: arial, sans;
}
.label{
font-size: 15px;
}
.legend text,
.axis text {
font-size: 13px;
fill: #333;
}
.axis path,
.axis line{
stroke-width: 1px;
stroke: #777;
}
</style>
<script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script type="text/javascript">
var margin = {top: 30, right: 50, bottom: 40, left:40};
var width = 960 - margin.left - margin.right;
var height = 500 - margin.top - margin.bottom;
var svg = d3.select('body')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var xScale = d3.scaleLinear().range([0, width]);
var yScale = d3.scaleLinear().range([height, 0]);
// il aurait plus judicieux de faire :
// var yScale = d3.scaleLinear().range([0, height]);
var xAxis = d3.axisTop().scale(xScale);
var yAxis = d3.axisLeft().scale(yScale);
var color = d3.scaleOrdinal(d3.schemeCategory20);
d3.csv('iris.csv', function(error, data){
data.forEach(function(d){
d.SepalLength = +d.SepalLength;
d.SepalWidth = +d.SepalWidth;
d.PetalLength = +d.PetalLength;
d.Species = d.Name;
});
xScale.domain(d3.extent(data, function(d){
return d.SepalLength;
})).nice();
yScale.domain(d3.extent(data, function(d){
return d.SepalWidth;
})).nice();
svg.append('g')
.attr('class', 'x axis')
.call(xAxis);
svg.append('g')
.attr('class', 'y axis')
.call(yAxis);
var mark = svg.selectAll('.mark')
.data(data)
.enter().append('rect')
.attr('class', 'mark')
.attr('x', function(d){return xScale(d.SepalLength);})
.attr('y', function(d){ return yScale(d.SepalWidth); })
.attr('height', function(d){ return d.PetalLength; })
.attr('width', function(d){ return d.PetalLength; })
.style('fill', function(d){ return color(d.Species); });
svg.append('text')
.attr('x', 2)
.attr('y', height + 5)
.attr('class', 'label')
.text('Sepal Width');
svg.append('text')
.attr('x', width)
.attr('y', 10)
.attr('text-anchor', 'end')
.attr('class', 'label')
.text('Sepal Length');
var legend = svg.selectAll('legend')
.data(color.domain())
.enter().append('g')
.attr('class', 'legend')
.attr('transform', function(d,i){
return 'translate(0,' + ((i * 20) + height-60.0) + ')';
});
legend.append('rect')
.attr('x', width)
.attr('width', 18)
.attr('height', 18)
.style('fill', color);
legend.append('text')
.attr('x', width - 6)
.attr('y', 9)
.attr('dy', '.35em')
.style('text-anchor', 'end')
.text(function(d){ return d; });
legend.on('click', function(type){
d3.selectAll('.mark')
.style('opacity', 0.15)
.filter(function(d){
return d.Species == type;
})
.style('opacity', 1);
})
})
</script>
</body>
</html>
https://d3js.org/d3.v4.min.js