2016-12-15 68 views
0

我有一個D3 JS圖表,它爲每個圓圈繪製圓圈並且每個圓圈的半徑在該特定的類中是NoOfStudents。如何改變圓的顏色回到原始顏色點擊另一個圓圈的D3 Js圖表

我添加了一個Click事件,它將把圓圈的顏色從「黑色」改變爲「lightcoral」。

我想要的功能是,如果我點擊第2圈(點擊第1圈後),然後休息所有圈子應該返回到原來的「黑色」顏色。

如何實現這一目標?謝謝!

//data 
 
let data = [{ "noOfStudent": 40, "class": "Class 1" }, { "noOfStudent": 30, "class": "Class 2" }, { "noOfStudent": 20, "class": "Class 3" }]; 
 
// set the dimensions and margins of the graph 
 
var margin = { top: 20, right: 20, bottom: 30, left: 40 }, 
 
    width = 960 - margin.left - margin.right, 
 
    height = 500 - margin.top - margin.bottom; 
 

 
// set the ranges 
 
var x = d3.scalePoint().range([0, width]).padding(0.4); 
 
var y = d3.scaleLinear().range([height, 0]); 
 

 
var svg = d3.select("body").append("svg").attr("style", "outline: thin solid red;") 
 
    .attr("width", width + margin.left + margin.right) 
 
    .attr("height", height + margin.top + margin.bottom) 
 
    .append("g") 
 
    .attr("transform", 
 
    "translate(" + margin.left + "," + margin.top + ")"); 
 

 
// get and format the data 
 
data.forEach(function (d) { 
 
    d.noOfStudent = +d.noOfStudent; 
 
}); 
 

 
// Scale the range of the data in the domains 
 
x.domain(data.map(function (d) { return d.class; })); 
 
y.domain([0, d3.max(data, function (d) { return d.noOfStudent; }) * 1.2]); 
 

 
// append the rectangles for the bar chart 
 
svg.selectAll(".bar") 
 
    .data(data) 
 
    .enter().append("circle") 
 
    .attr("class", "bar") 
 
    .attr("cx", function (d) { return x(d.class); }) 
 
    .attr("cy", function (d) { return y(d.noOfStudent); }) 
 
    .attr("r", function (d) { return d.noOfStudent; }) 
 
    .text(function (d) { return d.noOfStudent; }) 
 

 
    .on("click", function (d) { 
 
     d3.select(this).attr('r', d.noOfStudent) 
 
      .style("fill", "lightcoral") 
 
    }); 
 

 
// add the x Axis 
 
svg.append("g").attr("transform", "translate(0," + height + ")").call(d3.axisBottom(x)); 
 

 
// add the y Axis 
 
svg.append("g").call(d3.axisLeft(y));

+0

點擊,選擇所有ci rcles,將它們着色爲黑色,然後選擇此圓形顏色此lightcoral – thatOneGuy

+0

每個圓圈選擇中都有一個API調用。我覺得選擇所有的圈子都會有問題 –

回答

1

給圈子的成員類以後選擇它們:

.attr("class", "bar allCircles") //i didnt use 'bar' on purpose as you may have used it elsewhere 

獨立的點擊功能,正如我在評論中所提到的,顏色各界黑話,點擊圈淺輕石:

circles.on("click", function (d) { 
     d3.selectAll('.allCircles').style('fill','black'); //fill all circles black 
     d3.select(this).style("fill", "lightcoral"); //then fill this circle lightcoral 
    }); 
+1

非常感謝,它按預期工作 –