checkbox

by nancynancy

HTML

<script src="https://d3js.org/d3.v4.min.js"></script>
<pre id="data">
color,clarity,count,heights
G,SI1,28,28
H,SI1,39,67
G,SI2,20,20
H,SI2,27,47
G,VS1,26,26
H,VS1,15,41
</pre>
<br>
<br>
<input class="myCheckbox" type="checkbox" value="G"> G
<input class="myCheckbox" type="checkbox" value="H"> H
<br>

<div id="content"></div>

CSS

body,html{
	margin: 0;
	padding: 0;
	font-family: "Arial", sans-serif;
	font-size: 0.95em;
	text-align: center;
	background-color: white;
}

pre {
  display:none;
  }

JavaScript

var margin = {top: 20, right: 20, bottom: 30, left: 20};        
var width = 200 - margin.left - margin.right;
var height = 150 - margin.top + margin.bottom;
var x = d3.scaleBand().rangeRound([0, width]).padding(0.5);
var y = d3.scaleLinear().range([height, 40]);
var xAxis = d3.axisBottom(x);
var yAxis = d3.axisLeft(y);
var color = d3.scaleOrdinal(d3.schemeCategory10);
var mydata = d3.csvParse(d3.select("pre#data").text());

d3.selectAll(".myCheckbox").on("change",update);
update();

////////////////// Function START ///////////////////////////////
function update() {
  ////////////////// SELECTIONS //////////////////////////////////
  var choices = [];
  d3.selectAll(".myCheckbox").each(function(d){
    cb = d3.select(this);
    if(cb.property("checked")){
      choices.push(cb.property("value"));
    }
  });
	console.log({choices});
  
  ////////////////// DATA FILTERING //////////////////////////////////
  if(choices.length > 0){
    newData = mydata.filter(function(d,i){return choices.includes(d.color);});
  } else {
    newData = mydata;     
  } 

	console.log({newData});
  ////////////////// PLOTTING FUNCTION //////////////////////////////
  
    x.domain(newData.map(function(d) { return d.clarity; }));
    y.domain([0, 40])

    newData.forEach(function(d){
        d.count = +d.count;
        d.heights = +d.heights;
      });

    var panelData = d3.nest()
      .key(function(d) { return d.color; })
      .entries(newData);

    var panelUpdate = d3.selectAll("svg.container")
          .data(panelData, d => d.key) 
          // instead of index, actual value of key
    
    var panel = panelUpdate
          .enter().append("svg") // magic!
          .attr("class", "container")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
          .append("g")
          .attr("transform", "translate(" + margin.left + "," +
          margin.top + ")");
          
    console.log({panelData});

 ...