【发布时间】:2018-07-29 17:32:00
【问题描述】:
我是初学者,我正在学习 d3.js,但我无法弄清楚如何根据来自 api 的 json 格式的数据绘制图形或代码。 这是我尝试过的事情之一,但我无法根据另一个 api 中的新数据进行更改。有谁能够帮助我? 我在哪里进行更改?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="960" height="500"></svg>
</head>
<style>
body {
text-align: center;
margin-top: 5em;
background-color: #74b9ff;
}
h1 {
color: snow;
}
</style>
<body>
<h1>Bitcoin Prices in U.S. Dollars</h1>
<script>
var url = "https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD&limit=200&aggregate=3&e=CCCAGG";
d3.json(url).get(function(error, d) {
var data = d.Data;
data.forEach(function(d){ d.time = new Date(d.time * 1000) });
if (error) throw error;
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleTime()
.range([0, width])
var y = d3.scaleLinear()
.range([height, 0]);
var line = d3.line()
.x(function(d) { return x(d.time); })
.y(function(d) { return y(d.close); });
x.domain(d3.extent(data, function(d) { return d.time; }));
y.domain(d3.extent(data, function(d) { return d.close; }));
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.attr("stroke-width", 2)
.attr("fill", "none")
.style("font-size",".8em");
g.append("g")
.call(d3.axisLeft(y))
.attr("stroke-width", 2)
.style("font-size",".8em")
.append("text")
.attr("fill", "#000")
.attr("transform", "rotate(-90)")
.attr("y", 20)
.attr("text-anchor", "end")
.attr("font-size", "1.2em")
.text("Price ($)")
g.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "#ffeaa7")
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke-width", 2)
.attr("d", line);
});
</script>
</body>
</html>
我得到了上述代码的正确输出,但我想将 api 更改为 https://blockchain.info/ticker
我可以在哪里进行更改以使其正常工作?
【问题讨论】:
-
它们是两个不同的数据集。一个随着时间的推移有多个值,因此您可以绘制一个漂亮的折线图。另一个是不同种类货币的属性。为此,您需要一个条形图。你想用
blockchain数据集显示什么? -
@rioV8 先生,我希望我的图表在每次来自 api 的 json 数据发生变化时发生变化。当我刷新时
-
@rioV8 我想通过图表查看比特币价格随时间的变化。当我刷新时,如果来自 api 的 json 数据发生变化,图表应该会发生变化。
-
是的,但是对于您的区块链 json 数据,折线图不是正确的,x 值是序数不是线性的。这是一个更好的图表bl.ocks.org/mbostock/3885304
-
@rioV8 是的,我看到了。但它的 .tsv 不是我正在研究的那个。但是我在哪里进行更改才能使我的图表正常工作?
标签: javascript json d3.js