给定以下数据数组,我如何使用 d3 在图表上显示这些数据,类似于提供的示例。
数据
我的数据在一个对象数组中,如下所示:
[
{
"key": "Brazil",
"value": 2
},
{
"key": "Denmark",
"value": 4
},
{
"key": "Sweden",
"value": 8
},
{
"key": "Japan",
"value": 10
},
{
"key": "Russia",
"value": 14
}
]
最终目标
我试过的
我想到目前为止最重要的是我的代码:
<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */
.line {
fill: none;
stroke: steelblue;
stroke-width: 3px;
}
</style>
<body>
<!-- load the d3.js library -->
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var dataset = [
{
"key": "Brazil",
"value": 2
},
{
"key": "Denmark",
"value": 4
},
{
"key": "Sweden",
"value": 8
},
{
"key": "Japan",
"value": 10
},
{
"key": "Russia",
"value": 14
}
];
// set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// set the ranges
var x = d3.scaleLinear().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
// define the line
var valueline = d3.line()
.x(function(d) { return x(width / dataset.length); })
.y(function(d) { return y(d.value); });
// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
function draw(data) {
data.forEach(function(d) {
d.key = d.key.toString();
d.value = +d.value;
});
data.sort(function(a, b){
return a["value"]-b["value"];
})
// Scale the range of the data
x.domain(d3.extent(data, function(d) { d.key; }));
y.domain([0, d3.max(data, function(d) { return d.value; })]);
// Add the valueline path.
svg.append("path")
.data(data)
.attr("class", "line")
.attr("d", valueline);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Add the Y Axis
svg.append("g")
.call(d3.axisLeft(y));
}
// trigger render
draw(dataset);
</script>
</body>
(我认为)问题在哪里
这段代码是我在过去几天看到的几个示例的合并,但是它们似乎都针对仅包含数字和/或日期的数据模型,例如沿轴的日期和沿x轴的值y。
- X 和 Y 变量/函数
正因为如此,我认为我的代码没有生成图表的原因之一是如何声明x和y变量。我已经阅读了 API 参考,但这并没有让我成功。
- 价值线变量/函数
一般来说,我认为这看起来不错,但是因为它使用了上面提到的 x & y 函数(我不完全理解),我不能确定。
- 设置域
我认为这是使用针对不同数据模型量身定制的各种不同示例的另一个后遗症,但我不确定。
概括
因此,我认为有一些区域导致我的图表几乎只显示 X 和 Y 轴,但是花了相当多的时间试图更好地理解 d3(使用似乎没有帮助的示例),我想我会转到堆栈溢出。如果你们能给我任何指示,那就太好了。
