d3.js折线图
by Sohaib Nehal
通过Sohaib Nehal
学习使用D3.js创建折线图 (Learn to create a line chart using D3.js)
使用D3.js的功能绘制漂亮的数据表示形式。 (Use the power of D3.js to draw beautiful representations of your data.)
D3.js is an open source JavaScript library used to create beautiful data representations which we can view in any modern browser. Using D3.js, we can create various kinds of charts and graphs from our data.
D3.js是一个开源JavaScript库,用于创建漂亮的数据表示形式,我们可以在任何现代浏览器中查看。 使用D3.js,我们可以根据数据创建各种图表。
In this tutorial, we are going to create a line chart displaying the Bitcoin Price Index from the past six months. We will be pulling in data from an external API and rendering a line chart with labels and an axis inside the DOM.
在本教程中,我们将创建一个折线图,显示过去六个月的比特币价格指数。 我们将从外部API提取数据,并在DOM内部绘制带有标签和轴的折线图。
We’ve also created a free D3.js course on Scrimba. Check it out here.
我们还在Scrimba上创建了免费的D3.js课程。 在这里查看。
入门 (Getting started)
First of all, we will import the D3.js library directly from the CDN inside our HTML.
首先,我们将直接从HTML内的CDN导入D3.js库。
<html> <head> <link rel="stylesheet" href="index.css"> </head> <body> <svg></svg> <script src="https://d3js.org/d3.v4.min.js"></script> </body></html>
We have also added an <svg>
</svg> tag inside our HTML to create the line chart inside it using D3.js
我们还在HTML内添加了<svg>
</ svg>标记,以使用D3.js在其中创建折线图。
Let’s now move towards writing our JavaScript code. First of all, we want to load our data of the Bitcoin Price Index from an external API once the DOM has been loaded.
现在,让我们开始编写我们JavaScript代码。 首先,一旦加载了DOM,我们想从外部API加载比特币价格指数数据。
获取数据 (Fetch Data)
var api = 'https://api.coindesk.com/v1/bpi/historical/close.json?start=2017-12-31&end=2018-04-01'