У меня есть гистограмма, которую я бы хотел:
1) При щелчке выбранная полоса меняет цвет [Код, который у меня работает]
2) Изменяется div круга цвет в зависимости от высоты панели [я не могу добавить это к приведенному выше коду]
Я знаю
.on('click', datum => { console.log(datum); })
Даст мне высоту баров, которую я хочу использовать для окраски бар, и что я могу использовать
.attr("fill", function (d) { return "rgb(0, 0, " + Math.round(d * 10) + ")"; })
Чтобы изменить цвет круга на основе высоты бара, но я изо всех сил пытаюсь собрать все эти кусочки кода вместе.
//Width and height
var w = 500;
var h = 100;
var barPadding = 1;
var dataset = [5, 10, 13, 19, 21, 25, 22, 18, 15, 13, 11, 12, 15, 20, 18, 17, 16, 18, 23, 25];
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("class", "allbars")
.attr("x", function (d, i) {
return i * (w / dataset.length);
})
.attr("y", function (d) {
return h - (d * 4);
})
.attr("width", w / dataset.length - barPadding)
.attr("height", function (d) {
return d * 4;
})
.attr("fill", "#2296F3")
/* clicking on the bar gives us the data but how do I use this to change the circle color
.on('click', datum => {
console.log(datum);
/*
d3.selectAll('the_circle')
.attr("fill", function (d) {
console.log(d)
return "rgb(0, 0, " + Math.round(d * 10) + ")";
})
})
/* This code can be used to change the bar color on click */
.on("click", function (d) {
d3.selectAll('.allbars').style('fill', '#2296F3'); //fill all circles black
d3.select(this).style("fill", "#012B4E"); //then fill this circle lightcoral
}
)
// Add circle SVG, give it class circle_data that will be effected by on click
map_svg = d3.select("#the_circle").append("svg")
.attr("class", "svgWrapper")
map_svg.append("circle")
.attr("class", "performer_circle")
.attr("cx",100)
.attr("cy", 100)
.attr("r", 50)
.attr("fill", "black");
body {
font-size: 19px;
font-family: 'Open Sans', sans-serif;
font-weight: 400;
text-align: center;
}
#title {
font-size: 20px;
padding-bottom: 10px;
padding-top: 20px;
font-weight: 300;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3: Adding dynamic color, based on data</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.13/d3.js"></script>
</head>
<body>
<div id="bars"></div>
<div id="the_circle"></div>
<div id="title">Clicking on a bar changes it's color, it also triggers the circle to change colors</div>
</body>
</html>