Built with blockbuilder.org
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<div>
<div id ="chart1" style="background-color: red; width: 400px; height: 300px; display: inline-block;"></div>
<div id ="chart2" style="background-color: blue; width: 391px; height: 300px; display: inline-block;"></div>
</div>
<script>
function create_scatterplot(el, data, var_x, var_y, size) {
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 200 - margin.left - margin.right,
height = 200 - margin.top - margin.bottom;
var x = d3.scaleLinear()
.range([0, width]);
var y = d3.scaleLinear()
.range([height, 0]);
var r = d3.scaleSqrt()
.range([2,10]);
var xAxis = d3.axisBottom()
.scale(x);
var yAxis = d3.axisLeft()
.scale(y);
var color = d3.scaleOrdinal(d3.schemeCategory20);
// si on veut avoir un contôle sur les couleurs, il faut faire color.domain(["virginica", etc]). Ici on a crée la range, et c'est seulement plus tard que l'on défini le domaine.
// color.domain ne contient que le nom des espèces
// la légende c'est data(color.domain()), donc les d ne contiennent que les noms des espèces
var symbols = d3.scaleOrdinal(d3.symbols);
// creates a generator for symbols
var symbol = d3.symbol().size(100);
var svg = el.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 tooltip = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
d3.csv('iris.csv', function(error, data){
data.forEach(function(d){
d.sepal_length = +d.sepal_length;
d.sepal_width = +d.sepal_width;
d.petal_length = +d.petal_length;
d.petal_width = +d.petal_width;
});
x.domain(d3.extent(data, function(d){
return d.sepal_length;
})).nice();
y.domain(d3.extent(data, function(d){
return d.sepal_width;
})).nice();
r.domain(d3.extent(data, function(d){
return d.petal_length;
})).nice();
// we use the ordinal scale symbols to generate symbols
// such as d3.symbolCross, etc..
// -> symbol.type(d3.symbolCross)()
svg.selectAll(".symbol")
.data(data)
.enter().append("path")
.attr("class", "symbol")
.attr("d", function(d, i) { return symbol.type(symbols(d.species))(); })
.style("fill", function(d) { return color(d.species); })
.attr("transform", function(d) {
return "translate(" + x(d.sepal_length) + "," + y(d.sepal_width) +")";
});
});
}
create_scatterplot(d3.select('#chart1')); //, data, var_x, var_y, size {}
create_scatterplot(d3.select('#chart2'));
</script>
</body>
https://d3js.org/d3.v4.min.js