【发布时间】:2020-10-30 18:46:39
【问题描述】:
我想在 d3.js 中做一个圆环图。基本上这个想法是写 3 个输入,它应该以这种方式显示:
不幸的是我做不到,我不确定如何在 javascript 代码中实现变量fuel、fuel 2 和fuel 3,我不确定它是否必须在html 代码或javascript 代码中指示.提前致谢。
<meta charset="utf-8">
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>
<div>
<input type="number" id="fuel" style="text-align:center">
</div>
<div>
<input type="number" id="fuel2" style="text-align:center">
</div>
<div>
<input type="number" id="fuel3" style="text-align:center">
</div>
<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>
var fuel = document.getElementById('fuel');
var fuel2 = document.getElementById('fuel2');
var fuel3 = document.getElementById('fuel3');
// set the dimensions and margins of the graph
var width = 450
height = 450
margin = 40
// The radius of the pieplot is half the width or half the height (smallest one). I subtract a bit of margin.
var radius = Math.min(width, height) / 2 - margin
// append the svg object to the div called 'my_dataviz'
var svg = d3.select("#my_dataviz")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// Create dummy data
var data = {fuel,fuel2,fuel3}
// set the color scale
var color = d3.scaleOrdinal()
.domain(data)
.range(["#98abc5", "#8a89a6", "#7b6888"])
// Compute the position of each group on the pie:
var pie = d3.pie()
.value(function(d) {return d.value; })
var data_ready = pie(d3.entries(data))
// Build the pie chart: Basically, each part of the pie is a path that we build using the arc function.
svg
.selectAll('whatever')
.data(data_ready)
.enter()
.append('path')
.attr('d', d3.arc()
.innerRadius(100) // This is the size of the donut hole
.outerRadius(radius)
)
.attr('fill', function(d){ return(color(d.data.key)) })
.attr("stroke", "black")
.style("stroke-width", "2px")
.style("opacity", 0.7)
``
【问题讨论】:
标签: javascript html css d3.js