javascript 图表_如何使用JSCharting制作第一个JavaScript图表

javascript 图表

When you're starting out as a beginner JavaScript developer, I think it is important to pursue interesting projects. That way you can make sure you have fun as you learn, and you'll likely find an area of specialization that you enjoy.

当您刚开始成为JavaScript开发人员时,我认为追求有趣的项目很重要。 这样一来,您可以确保自己在学习中获得乐趣,并且可能会找到自己喜欢的专业领域。

As they say, "If you love what you do, you'll never work a day in your life".

正如他们所说: “如果您热爱自己的工作,那么您就永远不会有一天工作 。”

In this article, I will introduce you to front-end data visualization, which is my personal passion. Perhaps it will become your passion as well!

在本文中,我将向您介绍前端数据可视化,这是我的个人爱好。 也许它将也成为您的激情!

The most rewarding moments for me as a developer are when I can see or experience the results of what I've made. It’s highly satisfying to create a chart that reveals interesting insights about its data, or an interactive experience that helps explore details of a unique data set. The more significant the result, the more rewarding it feels.

作为开发人员,对我来说最有意义的时刻是当我看到或体验所取得的成果时。 创建一个图表以显示有关其数据的有趣见解,或有助于探索独特数据集细节的交互式体验,这是令人非常满意的。 结果越重要,则感觉就越有意义。

However, I have realized that the amount of work you put into a project does not necessarily correlate with the sense of accomplishment – sometimes it feels great even when it was relatively easy.

但是,我已经意识到,您投入到项目中的工作量并不一定与成就感相关联-有时即使相对容易,也会感觉很棒。

Over time, you will find tools that will help make you more efficient, and sometimes you will move mountains with little effort. There are many chart libraries and tools available in the data visualization field. With the right tools, you will create new charts with little effort, regardless of the type of chart you need. Personally, I think that datavis yields a great reward on your investment of time and effort.

随着时间的流逝,您会发现有助于提高工作效率的工具,有时您会毫不费力地搬山。 数据可视化字段中有许多图表库和工具可用。 使用正确的工具,无论使用哪种图表,您都可以轻松创建新图表。 我个人认为,datavis可以为您的时间和精力投入带来丰厚的回报。

In this tutorial you will use a number of tools to get data over the internet, process it, and draw a beautiful chart that can be viewed in any modern browser. You can click the links below to download example code for each step individually, view them all on GitHub, or download all steps at once here: all-steps.zip.

在本教程中,您将使用多种工具通过Internet获取数据,对其进行处理,并绘制出可以在任何现代浏览器中查看的漂亮图表。 您可以单击下面的链接单独下载每个步骤的示例代码,在GitHub上查看它们,或在此处一次性下载所有步骤: all-steps.zip

结果 (The Result)

By the end of this tutorial you will create this interactive data-driven chart. You will learn how to get data over the internet, process it, and make a chart with that data. You will also be able to make your own charts from scratch.

在本教程结束时,您将创建此交互式数据驱动的图表。 您将学习如何通过Internet获取数据,进行处理以及如何使用这些数据制作图表。 您还可以从头开始制作自己的图表。

After processing the data and charting it, you will also learn how to make adjustments to the chart including modifying the default legend, enabling x axis crosshairs with tooltips, and applying text annotations to add context and other information to the chart.

在处理完数据并绘制图表之后,您还将学习如何对图表进行调整,包括修改默认图例,使用工具提示启用x轴十字准线以及应用文本注释向图表添加上下文和其他信息。

工具 (The Tools)

To get started, use an internet browser like the one you're probably using to read this article. I recommend Chrome as it offers a great experience and built in tools for developers.

首先,请使用您可能正在阅读本文的Internet浏览器。 我建议您使用Chrome,因为它可以为开发人员提供出色的体验并内置了工具。

Next you will need a text editor. Something as simple as notepad will work. But, I suggest using a more advanced code editor such as VS Code, as this is an environment you will spend a lot of time with. It will give you a more convenient and pleasant coding experience, and it makes writing HTML5, CSS, and JavaScript easier on the eyes. Most important, if you forget a quote or comma somewhere, a code editor can help you find the error.

接下来,您将需要一个文本编辑器。 记事本之类的简单操作即可。 但是,我建议使用更高级的代码编辑器,例如VS Code,因为这是一个您将花费大量时间的环境。 它将为您提供更方便和愉悦的编码体验,并使编写HTML5,CSS和JavaScript更加容易。 最重要的是,如果您忘记了某个地方的引号或逗号,则代码编辑器可以帮助您找到错误。

This article can help you choose the best JavaScript code editor for web development.

本文可以帮助您选择最佳JavaScript代码编辑器进行Web开发

You will use the JSCharting chart library to automatically draw and add interactive functionality for this chart. No other JavaScript libraries such as jQuery, or front-end platforms including React and Angular (commonly used for website projects) will be required.

您将使用JSCharting图表库为该图表自动绘制并添加交互功能。 不需要其他JavaScript库(如jQuery)或前端平台(包括React和Angular)(通常用于网站项目)。

为什么选择JSCharting? (Why JSCharting?)

JSCharting is a JavaScript charting library that can draw many different types of charts using SVG. It is easy to use and get started with, so it's a good fit for this tutorial. The API (Application Programming Interface, aka the options and settings necessary to create charts) makes difficult things simpler and it is a good option when experimenting with data visualizations.

JSCharting是一个JavaScript图表库,可以使用SVG绘制许多不同类型的图表。 它易于使用和入门,因此非常适合本教程。 API(应用程序编程接口,又名创建图表所必需的选项和设置)使事情变得更简单,并且在尝试数据可视化时是个不错的选择。

You can use JSCharting for free for personal and commercial use with the included branding.

您可以免费使用带有随附商标的JSCharting用于个人和商业用途。

You can create responsive charts with JSCharting through a couple simple steps:

您可以通过几个简单的步骤使用JSCharting创建响应式图表:

  • Define a <div> tag in the HTML file with a unique id.

    在HTML文件中定义具有唯一ID的<div>标记。

  • Provide this id, data, and any other options when calling JSC.Chart() in the JavaScript file.

    在JavaScript文件中调用JSC.Chart()时,请提供此ID,数据和任何其他选项。

That's it. JSC will draw a professional looking chart populating this div tag with SVG element visuals. The chart will be responsive and interactive without any extra effort.

而已。 JSC将绘制一张专业外观的图表,并使用SVG元素视觉效果填充此div标签。 该图表将具有响应性和交互性,无需任何额外的努力。

数据 (The Data)

You will use a data file provided by the NCHS (National Center for Health Statistics) listing historical life expectancy of males and females in the US.

您将使用由NCHS(国家卫生统计中心)提供的数据文件,其中列出了美国男性和女性的历史预期寿命。

You can find it here: https://data.cdc.gov/resource/w9j2-ggv5.csv.

您可以在这里找到它: https : //data.cdc.gov/resource/w9j2-ggv5.csv

This CSV file contains data that categorizes the life expectancies by year, race, and sex. You will use some of this data to draw a simple male/female trend line over the last 100 years.

此CSV文件包含按年龄,种族和性别分类的预期寿命数据。 您将使用其中一些数据来绘制过去100年中的简单的男性/女性趋势线。

CSV (Comma Separated Values) is a great format for transmitting data over the internet. It is compact, human readable and you can open it directly excel, which is also nice.

CSV(逗号分隔值)是一种通过Internet传输数据的绝佳格式。 它结构紧凑,易于阅读,您可以直接使用excel打开它,这也很好。

So without further ado, let's get started.

因此,事不宜迟,让我们开始吧。

第1步-添加空白图表 (Step 1 - Add a blank chart)

The first zip file contains a blank starting point you can fill in as we go. If you get lost or confused, or want to skip ahead, the zip file at the end or throughout each section will bring you up to speed.  

第一个zip文件包含一个空白的起点,您可以随时进行填写。 如果您迷路或困惑,或者想跳过,则末尾或每个部分的zip文件将使您快速入门。

If you wish to download all the files at once, see all-steps.zip instead.

如果您希望一次下载所有文件,请参阅all-steps.zip 相反

step1-a.zip (step1-a.zip)

This zip file contains the following files.

该zip文件包含以下文件。

  • index.html

    index.html

  • js/index.js

    js/index.js

The .html file is empty except for some standard code that makes it a valid file and the .js file is completely blank.

.html文件为空,除了一些使它成为有效文件的标准代码外, .js文件完全为空。

The first step is to add some scripts to the HTML web page file. Normally people suggest adding <script> tags inside the <head> tags. However, for scripts that affect the HTML content it is often better to add them after the closing </body> tag.

第一步是向HTML网页文件中添加一些脚本。 通常,人们建议在<head>标签内添加<script> <head>标签。 但是,对于影响HTML内容的脚本,通常最好在</body>标记后添加它们。

This technique loads all the HTML into the DOM before executing any JavaScript. The chart needs the HTML loaded before it can draw in it. The DOM (Document Object Model) is a representation of your HTML code in the browser memory. Once HTML is loaded into the DOM the browser can display it and JavaScript can interact with it.

该技术在执行任何JavaScript之前将所有HTML加载到DOM中。 图表需要加载HTML才能绘制。 DOM(文档对象模型)是浏览器内存中HTML代码的表示。 将HTML加载到DOM后,浏览器可以显示它,而JavaScript可以与其交互。

Start by adding the JSCharting library to the HTML file. Open the index.html file in your editor of choice. Then add a script tag to include JSCharting after the closing </body> tag. The resulting code at the bottom of the file should look like this:

首先将JSCharting库添加到HTML文件。 在您选择的编辑器中打开index.html文件。 然后,在</body>标记后添加一个脚本标记以包含JSCharting。 文件底部的结果代码应如下所示:

</body>
<script src="https://code.jscharting.com/2.9.0/jscharting.js"></script>
</html>

This library URL points to a CDN (Content Delivery Network). It hosts the chart code and makes it convenient to quickly add the library to any HTML page for prototyping charts and experimenting. You can also download and use the library locally or use the npm package in your project, but the CDN does not require any extra steps.

该库URL指向CDN(内容交付网络)。 它托管了图表代码,使您可以方便地将库快速添加到任何HTML页面中,以制作图表原型和进行实验。 您也可以在本地下载和使用该库,也可以在项目中使用npm软件包,但是CDN不需要任何其他步骤。

Next, using the same technique, add another script tag referencing your blank JavaScript file. Add this script after the jscharting.js script so it looks like this:

接下来,使用相同的技术,添加另一个脚本标签,该脚本标签引用您的空白JavaScript文件。 在jscharting.js脚本之后添加此脚本,如下所示:

</body>
<script src="https://code.jscharting.com/2.9.0/jscharting.js"></script>
<script src="js/index.js"></script>
</html>

Great. We are almost ready to draw a blank chart. The last thing you need to do is add a <div> placeholder inside the HTML file to define where we want this chart to draw.

大。 我们几乎准备绘制空白图表。 您需要做的最后一件事是在HTML文件中添加一个<div>占位符,以定义我们希望此图表绘制的位置。

Add this HTML code inside the <body> tags.

将此HTML代码添加到<body>标记内。

<body>
    <div id="chartDiv" style="width:50%; height:300px; margin:0 auto;"></div>
</body>

The div must have an id so you can tell the chart which div to draw in. In this case the id is chartDiv.

div必须具有一个id,以便您可以告诉图表要绘制的div。在这种情况下,id为chartDiv

You may notice the style attribute of the <div> tag. It makes the div 50% of the window width, and 300 pixels tall. The margin style margin:0 auto; centers the div on the page. The chart will fill whatever size the div is, so changing the div size is a good way to control the chart size.

您可能会注意到<div>标记的样式属性。 它使div的窗口宽度为50%,高度为300像素。 边距样式margin:0 auto; 使div在页面上居中。 图表将填充div的任何大小,因此更改div的大小是控制图表大小的好方法。

You're all set with the HTML file. Open the index.js file and add a blank chart to this page by writing the following code which includes the div id chartDiv:

HTML文件全都设置好了。 通过编写以下包含div id chartDiv代码,打开index.js文件并向该页面添加空白图表:

JSC.Chart('chartDiv', {});

Open the index.html file in a browser (drag and drop the file into a web browser like chrome).

在浏览器中打开index.html文件(将其拖放到chrome等网络浏览器中)。

Not much to see yet, but you might notice a small JSC logo on this page. That indicates a chart is wired up and drawing.

没什么可看的,但是您可能会在此页面上注意到一个小的JSC徽标。 这表示图表已连接并绘制。

step1-b.zip

step1-b.zip

步骤2-稍微玩一下图表 (Step 2 - Play with the chart a little bit)

Ok, as a test, let's add a couple values for the chart to visualize to see how it works.

好的,作为测试,让我们为图表添加几个值以使其可视化以查看其工作方式。

Going back to the index.js file, replace the content with the following code which adds more options to the chart.

回到index.js文件,用以下代码替换内容,该代码向图表添加更多选项。

JSC.Chart('chartDiv', {
   type: 'horizontal column',
   series: [
      {
         points: [
            {x: 'Apples', y: 50},
            {x: 'Oranges', y: 42}
         ]
      }
   ]
});

Now refresh (F5) the browser window where the index.html page is loaded.

现在刷新(F5)加载index.html页面的浏览器窗口。

Nice! You just made your first chart using JavaScript.

真好! 您刚刚使用JavaScript制作了第一个图表。

You made a bar chart by setting the chart type option to 'horizontal column'. If you prefer a vertical column, set the value to 'column'. You also added a series with two points to the chart for Apples and Oranges.

通过将“图表类型”选项设置为'horizontal column'来制作条形图。 如果您希望使用垂直列,请将值设置为'column' 。 您还为苹果和橙子图表添加了两个点的系列。

All chart data is made up of series and points. A series is simply a group of data points. Charts can contain one or more data series. Data points consist of values that map to the x and y axes. Points can also include many other descriptive variables and values.

所有图表数据均由系列和点组成。 系列只是一组数据点。 图表可以包含一个或多个数据系列。 数据点由映射到x和y轴的值组成。 点还可以包括许多其他描述性变量和值。

The example above contains only one series. Now let's look at the options for a chart with two series. Replace the content of the JavaScript file with this code.

上面的示例仅包含一个系列。 现在,让我们看一下具有两个系列的图表的选项。 用此代码替换JavaScript文件的内容。

JSC.Chart('chartDiv', {
   type: 'horizontal column',
   series: [
      {
         name:'Andy',
         points: [
            {x: 'Apples', y: 50},
            {x: 'Oranges', y: 32}
         ]
      },{
         name:'Anna',
         points: [
            {x: 'Apples', y: 30},
            {x: 'Oranges', y: 22}
         ]
      }
   ]
});

Refreshing the browser window will show this chart.

刷新浏览器窗口将显示此图表。

The chart options look similar. Still a bar chart, but this time there is an extra object in the series array.  We also added name properties for each series so the chart can identify them in the legend.

图表选项看起来相似。 仍然是条形图,但是这次系列数组中有一个额外的对象。 我们还为每个系列添加了名称属性,以便图表可以在图例中识别它们。

If you are interested in making different charts like radar charts, area charts, pie charts, gantt charts, or even calendar heatmap charts, take a look at the JSCharting examples gallery and the source code (chart options) used to create those charts. You can quickly learn how to use other chart features by copying the available examples.

如果您有兴趣制作不同的图表,例如雷达图,面积图,饼图,甘特图,甚至日历热图图,请查看JSCharting示例库和用于创建这些图的源代码(图表选项)。 通过复制可用的示例,您可以快速学习如何使用其他图表功能。

step2.zip

step2.zip

第3步-准备数据 (Step 3 - Prepare the data)

The CSV data format is exactly that – Comma Separated Values. The file contains rows (lines) and each row represents a record or entry. Normally the first row of values contains the names of each comma separated value (column). Subsequent rows contain the values themselves.

CSV数据格式就是这样-逗号分隔值。 该文件包含行(行),每行代表一个记录或条目。 通常,值的第一行包含每个逗号分隔值(列)的名称。 随后的行包含值本身。

name,age
chris,26
mike,34

CSV is human readable, but there are variations of this format. Sometimes if values contain commas (e.g. mailing addresses) the format doesn't work as-is so each value is also wrapped in quotes. That way the commas inside quotes are ignored and the format can still work by using only the commas outside of quotes to separate the values.

CSV是人类可读的,但是这种格式有些变化。 有时,如果值包含逗号(例如,邮寄地址),则格式不能按原样工作,因此每个值也都用引号引起来。 这样,引号内的逗号将被忽略,并且仅使用引号外的逗号来分隔值,格式仍然可以工作。

"name","age","parents"
"Chris","26","Gregory, Mary"
"Mike","34","David, Sarah"

Values can also be separated using a different character like tabs in place of commas.

也可以使用其他字符(如制表符)代替逗号来分隔值。

But let's not get bogged down in minutia. JSCharting provides a number of tools that help with this process and we will use one of them to skip worrying about the CSV file format and convert it to JSON (JavaScript Object Notation). The result will be an array of objects. Each object represents a row with named properties. The first row in the CSV file is used to define the names of those properties.

但是,不要让细节陷入僵局。 JSCharting提供了许多有助于此过程的工具,我们将使用其中的一个来跳过对CSV文件格式的担心,并将其转换为JSON(JavaScript对象表示法)。 结果将是一个对象数组。 每个对象代表具有命名属性的行。 CSV文件中的第一行用于定义这些属性的名称。

This is the url of the data we are interested in: https://data.cdc.gov/resource/w9j2-ggv5.csv.

这是我们感兴趣的数据的URL: https : //data.cdc.gov/resource/w9j2-ggv5.csv

You can click to download and open it in excel.

您可以单击下载并在excel中打开。

However, you will download and access this CSV data in real-time using JavaScript code. The code below may be slightly confusing at first, but it's short and you can reuse it to get any CSV, text, or JSON files over the internet programmatically. It is similar to the older AJAX technology but much simpler to use.

但是,您将使用JavaScript代码实时下载和访问此CSV数据。 首先,下面的代码可能会有些混乱,但是它很短,您可以重复使用它以编程方式通过Internet获取任何CSV,文本或JSON文件。 它类似于较旧的AJAX技术,但使用起来更简单。

Once again, replace the content of the index.js file with the following:

再次用以下内容替换index.js文件的内容:

fetch('https://data.cdc.gov/resource/w9j2-ggv5.csv')
   .then(function (response) {
      return response.text();
   })
   .then(function (text) {
	csvToSeries(text);
   })
   .catch(function (error) {
      //Something went wrong
      console.log(error);
   });

function csvToSeries(text) {
   console.log(text);
}

Why so complicated? It is because when you request a file, it does not immediately become available. There is a delay and you have to wait for the file to arrive. So first you request the file from another website using fetch().

为什么这么复杂? 这是因为当您请求文件时,该文件不会立即可用。 有一个延迟,您必须等待文件到达。 因此,首先您使用fetch()从另一个网站请求文件。

fetch('https://data.cdc.gov/resource/w9j2-ggv5.csv')

Then the code inside the then(...) argument function gets called with the response when it arrives. This function converts the response into text and returns it, which passes the result to the following then() argument function.

然后, then(...)参数函数中的代码在到达时便随响应一起调用。 该函数将响应转换为文本并将其返回,然后将结果传递给随后的then()参数函数。

.then(function (response) {
	return response.text();
})

The next then(...) argument function calls the csvToSeries() function, and passes the text as an argument.

下一个then(...)参数函数调用csvToSeries()函数,并将文本作为参数传递。

.then(function (text) {
	csvToSeries(text);
})

In the catch() function, you can specify what to do if anything goes wrong. For example maybe the internet is down, or the URL is not correct.

catch()函数中,您可以指定出现任何问题时的处理方法。 例如,可能互联网中断,或URL不正确。

.catch(function (error) {
	//Something went wrong
	console.log(error);
});

In this case, the error is sent to the console.

在这种情况下,错误将发送到控制台。

In the csvToSeries() function we pass this text to the console for inspection.

csvToSeries()函数中,我们将此文本传递到控制台进行检查。

function csvToSeries(text) {
   console.log(text);
}

💡 Note: The native fetch() function is not supported in Internet Explorer 11. If you want to support this browser as well, you can use the JSC.fetch() function which comes with JSCharting. It provides the same functionality, but adds additional support for IE11.

注意: Internet Explorer 11不支持本机fetch()函数。如果您还希望支持此浏览器,则可以使用JSC.fetch()附带的JSC.fetch()函数。 它提供了相同的功能,但是增加了对IE11的额外支持。

Drag the index.html file into a browser window (or refresh the page if already open) and press F12. This will open the DevTools window of the chrome browser. By default, the bottom half of the DevTools window will show the console output. This is where the text is sent when you run code like:

index.html文件拖到浏览器窗口中(如果已经打开,则刷新页面),然后按F12键。 这将打开Chrome浏览器的DevTools窗口。 默认情况下,DevTools窗口的下半部分将显示控制台输出。 运行以下代码时,将在此处发送文本:

console.log(text);

You can also paste or write code into this console window to execute it. Try pasting the entire code snippet above into the console window (next to the > character) and press enter. You will notice you get the same result in the console window output. This can be useful for testing a line of code and experimenting.

您也可以将代码粘贴或写入此控制台窗口中以执行它。 尝试将上面的整个代码片段粘贴到控制台窗口中(>字符旁边),然后按Enter键。 您会注意到在控制台窗口输出中得到的结果相同。 这对于测试一行代码和进行实验很有用。

step3-a.zip

step3-a.zip

At this point you have retrieved the text of the CSV file over the internet and sent it to the console to prove that it works. Now we can start to work with it.

此时,您已经通过Internet检索了CSV文件的文本,并将其发送到控制台以证明它可以工作。 现在我们可以开始使用它了。

Let's take a look at this data file to get an idea of what's inside: https://data.cdc.gov/resource/w9j2-ggv5.csv

让我们看一下这个数据文件,以了解其中的内容: https : //data.cdc.gov/resource/w9j2-ggv5.csv

I used excel to sort the rows by the year column to analyze the rows of data for a single year.

我使用excel按年份列对行进行排序,以分析单个年份的数据行。

Each year contains 9 rows with data based on race and sex. We are only interested in the highlighted male and female values of all races for each year. You will create two series based on the highlighted rows. A series for female and one for male values.

每年包含9行,其中包含基于种族和性别的数据。 我们只对每年所有种族中突出的男性和女性价值观感兴趣。 您将基于突出显示的行创建两个系列。 女性系列,男性价值观。

Now that you have an idea of what needs to happen, let's get started.

现在您已经知道需要做什么,让我们开始吧。

First, let's use the JSC.csv2Json() function to convert the text into JSON format and pass it to the console to see what it does.

首先,让我们使用JSC.csv2Json()函数将文本转换为JSON格式,然后将其传递到控制台以查看其功能。

Update the csvToSeries() function with the following code:

使用以下代码更新csvToSeries()函数:

function csvToSeries(text) {
   let dataAsJson = JSC.csv2Json(text);
   console.log(dataAsJson)
}

Refresh the browser to see the updated console output.

刷新浏览器以查看更新的控制台输出。

The console shows an array of 1062 records. And this is one of these records:

控制台显示了1062条记录的数组。 这是这些记录之一:

{year: 1900, race: "All Races", sex: "Both Sexes", average_life_expectancy: 47.3, mortality: 2518}

💡 Note: The console can display arrays, and objects for inspection and you can expand and collapse sections in the console to explore details.

💡 注意:控制台可以显示阵列和对象以供检查,您可以在控制台中展开和折叠部分以浏览详细信息。

The property name average_life_expectancy is a little long, but you will need to use it. To avoid typing it more than once, define a constant variable to store this name. When you need to use this property, you can just write the variable name lifeExp. It will look like this row[lifeExp] instead of row.average_life_expectancy.

属性名称average_life_expectancy有点长,但是您将需要使用它。 为避免多次键入,请定义一个常量变量来存储此名称。 当需要使用此属性时,只需编写变量名称lifeExp 。 看起来像是row[lifeExp]而不是row.average_life_expectancy

Add this line at the top of the csvToSeries() function.

将此行添加到csvToSeries()函数的顶部。

function csvToSeries(text) {
	const lifeExp = 'average_life_expectancy';
	...

You can process this data using simple vanilla JavaScript. The end result we want is two series with data points that include a year and life expectancy for each point.

您可以使用简单的原始JavaScript处理这些数据。 我们想要的最终结果是两个系列的数据点,其中包括每个点的年份和预期寿命。

Update the csvToSeries() with the following code:

使用以下代码更新csvToSeries()

function csvToSeries(text) {
	const lifeExp = 'average_life_expectancy';
	let dataAsJson = JSC.csv2Json(text);
	let male = [], female = [];
	dataAsJson.forEach(function (row) {
		 //add either to male, female, or discard.
		console.log(row);
	});
}

It defines arrays for male and female data points. Then it calls the array dataAsJson.forEach() function passing a callback function(row){...} function as the argument. The forEach() function will execute the callback function for each item in the dataAsJson array. For now we will just call console.log(row) on each row that the callback function encounters.

它定义了男性和女性数据点的数组。 然后,它通过传递回调function(row){...}作为参数来调用dataAsJson.forEach()函数数组。 forEach()函数将对dataAsJson数组中的每个项目执行回调函数。 现在,我们仅在回调函数遇到的每一行上调用console.log(row)

Refresh the browser and inspect the console output.

刷新浏览器并检查控制台输出。

Let's add some logic to filter the data we want and log the result in the console window. Replace the csvToSeries() function with this code.

让我们添加一些逻辑来过滤所需的数据,并将结果记录在控制台窗口中。 用此代码替换csvToSeries()函数。

function csvToSeries(text) {
	const lifeExp = 'average_life_expectancy';
	let dataAsJson = JSC.csv2Json(text);
	let male = [], female = [];
	dataAsJson.forEach(function (row) {
		 //add either to male, female, or discard.
		if (row.race === 'All Races') {
			if (row.sex === 'Male') {
				male.push({x: row.year, y: row[lifeExp]});
			} else if (row.sex === 'Female') {
				female.push({x: row.year, y: row[lifeExp]});
			}
		}
	});
    console.log([male, female]);
}

Inside the callback function you decide whether the row is of interest and use it or if not then discard it.

在回调函数中,您可以确定该行是否有意义并使用它,如果不行,则将其丢弃。

if (row.race === 'All Races') {
	if (row.sex === 'Male') {
		//add data to male array
		male.push({x: row.year, y: row[lifeExp]});
	} else if (row.sex === 'Female') {
		//add data to female array
		female.push({x: row.year, y: row[lifeExp]});
	}
}

The logic checks to see if the row.race value equals 'All Races'. If so, then it checks to see if the row.sex property equals either 'Male' or 'Female'. If the row equals either, it adds the data to either the male or female arrays as a {x, y} point object. Notice the use of the lifeExp variable defined above which helps shorten this code.

逻辑检查以查看row.race值是否等于“ All Races”。 如果是这样,则它将检查row.sex属性是否等于“ Male”或“ Female”。 如果该行相等,则将数据作为{x, y}点对象添加到malefemale数组中。 请注意,上面定义的lifeExp变量的使用有助于缩短此代码。

At the end, you used console.log([male, female]) to pass the male and female variables to the console for inspection and to make sure your code worked as expected.

最后,您使用console.log([male, female])将公变量和母变量传递到控制台进行检查,并确保您的代码按预期工作。

After refreshing the browser, the console shows the result which is two arrays, each with 118 data points spanning the years 1900 to 2017.

刷新浏览器后,控制台将显示结果,该结果是两个数组,每个数组包含1900年至2017年的118个数据点。

Lastly, instead of passing the result to the console, wrap these data points within an array of two series that the chart can use directly and return them.

最后,不要将结果传递给控制台,而是将这些数据点包装在两个系列的数组中,图表可以直接使用它们并将其返回。

Add this code at the end of the csvToSeries() function:

csvToSeries()函数的末尾添加以下代码:

return [
   {name: 'Male', points: male},
   {name: 'Female', points: female}
];

If the returned value was sent to the console, it would produce this result.

如果将返回值发送到控制台,它将产生此结果。

As you can see, the logic for filtering rows is fairly simple and you can adjust it to get other details from this data set.

如您所见,筛选行的逻辑非常简单,您可以对其进行调整以从该数据集中获取其他详细信息。

To learn more about handling CSV files using JSCharting utilities, see this tutorial. When you are ready for more advanced data handling, the JSC.nest() utility can be used to create series and points from JSON data with with very little code.

要了解有关使用JSCharting实用程序处理CSV文件的更多信息,请参阅本教程 。 当您准备好进行更高级的数据处理时,可以使用JSC.nest()实用工具以很少的代码从JSON数据创建序列和点。

step3-b.zip

step3-b.zip

步骤4-全部放在一起 (Step 4 - Putting it all together)

The data handling section was the most difficult step, but that alone will enable you to manipulate and extract data of interest from any CSV file. This is where it all comes together and where you will feel a sense of accomplishment.

数据处理部分是最困难的步骤,但是仅此一步就可以使您从任何CSV文件中操作和提取感兴趣的数据。 这是一切融合在一起的地方,您将感受到成就感。

Start by adding a renderChart() function to the end of the index.js file. You will pass the series data to this function as an argument.

首先在index.js文件的末尾添加一个renderChart()函数。 您将系列数据作为参数传递给此函数。

function renderChart(series){
   JSC.Chart('chartDiv', {
      series: series
   });
}

In the then() argument function that calls csvToSeries(), pass the series result to the renderChart() function to see what it draws in the browser.

在调用csvToSeries()then()参数函数中,将系列结果传递给renderChart()函数,以查看其在浏览器中绘制的内容。

.then(function (text) {
	let series = csvToSeries(text);
	renderChart(series);
})

step4-a.zip

step4-a.zip

Now, refresh the browser. You should see this chart that uses the CSV data you processed in the previous section. Sweet! 😆

现在,刷新浏览器。 您应该看到使用上一部分中处理的CSV数据的图表。 甜! 😆

Whoa, what happened in 1918? Life expectancy dropped significantly there. According to Wikipedia there was a flu pandemic involving H1N1 virus that wiped out a portion of the world population. This unfortunate event shows how visualizing data provides insights you would not normally get from just looking at the numbers.

哇,1918年发生了什么事? 那里的预期寿命显着下降。 根据Wikipedia的说法,涉及H1N1病毒的流感大流行消灭了一部分世界人口。 这个不幸的事件表明,可视化数据如何提供通常仅查看数字通常无法获得的见解。

You created a chart using the default line series type and it looks good, but you can make a few adjustments and tweaks to further improve it.

您使用默认的线系列类型创建了一个图表,它看起来不错,但是您可以进行一些调整和调整以进一步改进它。

First, add a title at the top to explain what the viewer is looking at and an annotation at the bottom of the chart to credit the data source. Update the JSC.Chart() constructor function to pass the following options:

首先,在顶部添加一个标题以解释查看者正在查看的内容,并在图表底部添加一个注释以注明数据源。 更新JSC.Chart()构造函数以传递以下选项:

function renderChart(series){
	JSC.Chart('chartDiv', {
		title_label_text: 'Life Expectancy in the United States',
		annotations: [{
			label_text: 'Source: National Center for Health Statistics',
			position: 'bottom left'
		}],
		series: series
	});
}

When you refresh the browser you can see the updated chart.

刷新浏览器时,您可以看到更新的图表。

You added an annotation with label text, and a position setting. We can use another annotation for the title as well, but it was easier to use the title label in this example.

您添加了带有标签文本和位置设置的注释。 我们也可以为标题使用另一个注释,但是在此示例中,使用标题标签更加容易。

It is easy to control the annotation position using values such as 'top right' or 'inside bottom right'. The 'inside' value means the annotation is placed inside the chart area where data is drawn. This box positions chart example demonstrates all the position setting options.

使用诸如'top right''inside bottom right'值来控制注释位置很容易。 'inside'值表示将批注放置在绘制数据的图表区域内。 此盒位置图示例演示了所有位置设置选项。

The legend shows the sum of point values for each series, but the sum is not important for this data set. You can reduce the legend columns to only show the icon and series name by using this setting:

图例显示每个系列的点值的总和,但总和对于此数据集并不重要。 您可以使用以下设置将图例列减少为仅显示图标和系列名称:

legend_template: '%icon,%name'

But you don't really need to use a legend at all. It will be cleaner to simply label the lines themselves. You can disable the legend, and tell the chart to write the series name on the last point of each line series with these chart options:

但是,您根本不需要使用图例。 简单地标记线路本身会更清洁。 您可以禁用图例,并使用以下图表选项告诉图表在每个线系列的最后一点上写系列名称:

legend_visible: false,
defaultSeries_lastPoint_label_text: '<b>%seriesName</b>',

The '%seriesname' token is one of many point related tokens that can be used in any point label text to show point details and calculations.

'%seriesname'标记是许多与点相关的标记之一 ,可以在任何点标签文本中使用它们来显示点详细信息和计算。

Finally, let’s enable the x axis crosshair combined tooltip to show the male and female life expectancy for any given year. On mobile devices, you can tap the chart to see the crosshair tooltip. When using a PC, tooltips display when hovering over the chart with your mouse pointer.

最后,让我们启用x轴十字线组合工具提示,以显示任何给定年份的男性和女性预期寿命。 在移动设备上,您可以点击图表以查看十字线工具提示。 使用PC时,将鼠标指针悬停在图表上时会显示工具提示。

xAxis_crosshair_enabled: true,

You may be wondering, what's with all those underscores in property names? This is not the actual property name. It's a shorthand way to write:

您可能想知道,属性名称中的所有下划线是什么? 这不是实际的属性名称。 这是一种写法:

xAxis: {crosshair: {enabled: true}},

You may find it more convenient to specify a setting with underscores and JSCharting will understand what you mean.

您可能会发现使用下划线指定设置更加方便,JSCharting会理解您的意思。

The default tooltip text is clear, but let's customize it slightly to make it our own.

默认的工具提示文本是清楚的,但让我们对其进行一些自定义以使其成为我们自己的文本。

Since the crosshair tooltip shows information about each point it crosses, the tooltip text is defined within the point options. The defaultPoint property defines point options that all points will inherit automatically.

由于十字准线工具提示显示有关其交叉的每个点的信息,因此在提示选项中定义了工具提示文本。 defaultPoint属性定义所有点将自动继承的点选项。

defaultPoint_tooltip: '%seriesName <b>%yValue</b> years',

For more information about this feature, check out the crosshair and combined tooltip tutorial.

有关此功能的更多信息,请查看十字准线和组合工具提示教程

When you apply all these options, your code will look similar to the following snippet. Replace the entire renderChart() function with this code.

当您应用所有这些选项时,您的代码将类似于以下代码片段。 用此代码替换整个renderChart()函数。

function renderChart(series){
	JSC.Chart('chartDiv', {
		title_label_text: 'Life Expectancy in the United States',
		annotations: [{
			label_text: 'Source: National Center for Health Statistics',
			position: 'bottom left'
		}],
        legend_visible: false,
		defaultSeries_lastPoint_label_text: '<b>%seriesName</b>',
		defaultPoint_tooltip: '%seriesName <b>%yValue</b> years',
		xAxis_crosshair_enabled: true,
		series: series
	});
}

Refresh the browser window once more.

再次刷新浏览器窗口。

You did it!

你做到了!

First you fetched CSV data using native JavaScript. You then converted it into JSON format and filtered the data into two series. With those series you created a beautiful interactive line chart using JSCharting and configured it to look professional.

首先,您使用本机JavaScript提取了CSV数据。 然后,您将其转换为JSON格式,并将数据过滤成两个系列。 在这些系列中,您使用JSCharting创建了漂亮的交互式折线图,并将其配置为专业。

You can customize and adjusted the charts further to meet your specific needs. Visit the JSCharting tutorials section to learn more about a specific topic, or find charts similar to what you want to make in the examples gallery and copy them to continue your data visualization journey.

您可以进一步自定义和调整图表以满足您的特定需求。 请访问JSCharting 教程部分,以了解有关特定主题的更多信息,或在示例库中找到与您想要制作的图表类似的图表,然后将其复制以继续进行数据可视化之旅。

If you run into problems working with JSCharting, feel free to contact the support team. They will be happy to guide you or help resolve any issues you may encounter.

如果您在使用JSCharting时遇到问题,请随时支持团队联系 。 他们将很乐意为您提供指导或帮助您解决可能遇到的任何问题。

step4-b.zip

step4-b.zip

奖金挑战 (Bonus Challenge)

We did not use all the data available in in that CSV file. Let's experiment with it for fun and practice.

我们并未使用该CSV文件中的所有可用数据。 让我们尝试一下它的乐趣和实践。

Create this chart using what you have learned.

使用所学知识创建此图表。

This zip file contains the answer:

此zip文件包含答案:

step5-bonus.zip

step5-bonus.zip

Can you think of other charts you can make with this data? Keep experimenting and enjoy every minute of it!

您能想到可以使用此数据制作的其他图表吗? 继续尝试并享受每一分钟!

翻译自: https://www.freecodecamp.org/news/how-to-make-your-first-javascript-chart/

javascript 图表

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值