Skip to content

Instantly share code, notes, and snippets.

@ruiyang123
Last active January 17, 2020 16:00
Show Gist options
  • Save ruiyang123/42de738f3d98884ae2b330f8502d9dc3 to your computer and use it in GitHub Desktop.
Save ruiyang123/42de738f3d98884ae2b330f8502d9dc3 to your computer and use it in GitHub Desktop.
ex3
license: mit
<!DOCTYPE html>
<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>
<script>
// Feel free to change or delete any of the code you see in this editor!
var margin = {top: 40,right: 20,bottom: 40,left: 20};
var width = 960 - margin.left - margin.right;
var height = 500 - margin.top - margin.bottom;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.csv("https://raw.githubusercontent.com/LyonDataViz/MOS5.5-Dataviz/master/data/iris.csv",
function(data){
console.log(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
})
console.log(data);
var x = d3.scaleLinear()
.domain([
d3.min(data,function(d){return d.sepal_length})
,d3.max(data,function(d){return d.sepal_length})])
.range([margin.left,width+margin.left]);
var y = d3.scaleLinear()
.domain([
d3.min(data,function(d){return d.sepal_width})
,d3.max(data,function(d){return d.sepal_width})])
.range([margin.top,height+margin.top]);
var spec = ["setosa","versicolor","virginica"] ;
var color = ["red","blue","green"];
var radius = d3.scaleSqrt()
.domain([
d3.min(data,function(d){return d.petal_length})
,d3.max(data,function(d){return d.petal_length})])
.range([1,8]);
;
var col = d3.scaleOrdinal(color,spec);
console.log(x(5.1))
svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx",function(d,i){return x(d.sepal_length)})
.attr("cy",function(d,i){return height -y(d.sepal_width)})
.attr("r",function(d,i){return radius(d.petal_length)})
.style("fill",function(d,i){ return col(d.species)})
.on("mouseover",function(d,i){
d3.selectAll("circle").style("opacity",.1)
d3.select(this).style("opacity",1 )
})
.on("click",function(d,i){
d3.select(this).style("fill","pink")
})
var xAxis = d3.axisBottom()
.scale(x);
var yAxis = d3.axisLeft()
.scale(y);
var posx = height - margin.top;
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + posx + ")")
.call(xAxis)
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
}
)
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment