Hvordan lage ditt første JavaScript-diagram med JSCharting

Når du begynner som en nybegynner JavaScript-utvikler, tror jeg det er viktig å forfølge interessante prosjekter. På den måten kan du sørge for at du har det gøy mens du lærer, og du vil sannsynligvis finne et spesialiseringsområde du liker.

Som de sier, "Hvis du elsker det du gjør, vil du aldri jobbe en dag i livet ditt" .

I denne artikkelen vil jeg introdusere deg for front-end datavisualisering, som er min personlige lidenskap. Kanskje det vil bli din lidenskap også!

De mest givende øyeblikkene for meg som utvikler er når jeg kan se eller oppleve resultatene av det jeg har laget. Det er veldig tilfredsstillende å lage et diagram som avslører interessant innsikt om dataene, eller en interaktiv opplevelse som hjelper deg med å utforske detaljer om et unikt datasett. Jo mer signifikant resultatet er, jo mer givende føles det.

Imidlertid har jeg innsett at mengden arbeid du legger ned i et prosjekt ikke nødvendigvis korrelerer med følelsen av prestasjon - noen ganger føles det bra selv når det var relativt enkelt.

Over tid vil du finne verktøy som vil bidra til å gjøre deg mer effektiv, og noen ganger vil du flytte fjell med liten innsats. Det er mange kartbiblioteker og verktøy tilgjengelig i datavisualiseringsfeltet. Med de riktige verktøyene vil du lage nye diagrammer med liten innsats, uavhengig av hvilken type diagram du trenger. Personlig tror jeg at datavis gir en stor belønning på investeringen din av tid og krefter.

I denne opplæringen vil du bruke en rekke verktøy for å få data over internett, behandle det og tegne et vakkert diagram som kan vises i enhver moderne nettleser. Du kan klikke på lenkene nedenfor for å laste ned eksempelkode for hvert trinn individuelt, se dem alle på GitHub , eller laste ned alle trinnene samtidig her: all-steps.zip.

Resultatet

Mot slutten av denne opplæringen vil du lage dette interaktive datadrevne diagrammet. Du vil lære å få data over internett, behandle det og lage et diagram med disse dataene. Du vil også kunne lage dine egne diagrammer fra bunnen av.

Interaktivt JavaScript-linjediagram

Etter å ha behandlet dataene og kartlagt dem, vil du også lære hvordan du kan gjøre justeringer i diagrammet, inkludert å endre standardforklaringen, aktivere kryss fra aksen med verktøytips og bruke tekstkommentarer for å legge til kontekst og annen informasjon i diagrammet.

Verktøyene

For å komme i gang, bruk en nettleser som den du sannsynligvis bruker til å lese denne artikkelen. Jeg anbefaler Chrome, da det gir en flott opplevelse og innebygde verktøy for utviklere.

Deretter trenger du en tekstredigerer. Noe så enkelt som notisblokk vil fungere. Men jeg foreslår at du bruker en mer avansert kodeditor som VS Code, da dette er et miljø du vil bruke mye tid på. Det vil gi deg en mer praktisk og behagelig kodeopplevelse, og det gjør det enklere å skrive HTML5, CSS og JavaScript. Viktigst, hvis du glemmer et sitat eller komma et sted, kan en kodeditor hjelpe deg med å finne feilen.

Denne artikkelen kan hjelpe deg med å velge den beste JavaScript-kodeditoren for nettutvikling.

Du vil bruke JSCharting-kartbiblioteket til å automatisk tegne og legge til interaktiv funksjonalitet for dette diagrammet. Ingen andre JavaScript-biblioteker som jQuery eller frontend-plattformer, inkludert React og Angular (ofte brukt for nettsideprosjekter), vil være påkrevd.

Hvorfor JSCharting?

JSCharting er et JavaScript-kartbibliotek som kan tegne mange forskjellige typer diagrammer ved hjelp av SVG. Det er enkelt å bruke og komme i gang med, så det passer godt for denne opplæringen. API (Application Programming Interface, også alternativene og innstillingene som er nødvendige for å lage diagrammer) gjør vanskelige ting enklere, og det er et godt alternativ når du eksperimenterer med datavisualiseringer.

Du kan bruke JSCharting gratis til personlig og kommersiell bruk med den medfølgende merkevaren.

Du kan lage responsive diagrammer med JSCharting gjennom et par enkle trinn:

  • Definer en tag i HTML-filen med en unik id.
  • Oppgi denne ID-en, dataene og andre alternativer når du ringer JSC.Chart()inn JavaScript-filen.

Det er det. JSC vil tegne et profesjonelt utseende diagram som fyller denne div-koden med SVG-elementvisuelle. Diagrammet vil være responsivt og interaktivt uten ekstra anstrengelse.

Dataen

Du vil bruke en datafil levert av NCHS (National Center for Health Statistics) som viser historisk forventet levealder for menn og kvinner i USA.

Du finner den her: //data.cdc.gov/resource/w9j2-ggv5.csv.

Denne CSV-filen inneholder data som kategoriserer forventet levealder etter år, rase og kjønn. Du vil bruke noen av disse dataene til å tegne en enkel mannlig / kvinnelig trendlinje de siste 100 årene.

CSV (Comma Separated Values) er et flott format for overføring av data over internett. Den er kompakt, lesbar for mennesker, og du kan åpne den direkte utmerke seg, noe som også er hyggelig.

Så uten videre, la oss komme i gang.

Trinn 1 - Legg til et tomt diagram

Den første zip-filen inneholder et tomt startpunkt du kan fylle ut mens vi går. Hvis du går deg vill eller er forvirret, eller vil hoppe videre, vil zip-filen på slutten eller gjennom hver seksjon gi deg fart.  

Hvis du ønsker å laste ned alle filene samtidig, se all-steps.zipi stedet .

step1-a.zip

Denne zip-filen inneholder følgende filer.

  • index.html
  • js/index.js

Den .htmlfilen er tomt bortsett fra noen standard kode som gjør det til en gyldig fil og .jsfil er helt blank.

Det første trinnet er å legge til noen skript i HTML-nettsidefilen. Normalt foreslår folk å legge til koder i kodene. For skript som påvirker HTML-innholdet, er det imidlertid ofte bedre å legge dem til etter den avsluttende koden.

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.

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 tag. The resulting code at the bottom of the file should look like this:

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.

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:

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

Add this HTML code inside the tags.

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

You may notice the style attribute of the 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.

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:

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

Open the index.html file in a browser (drag and drop the file into a web browser like 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.

JSCharting logo shows the chart is working

step1-b.zip

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.

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.

Horizontal column chart with one series and two points

Nice! You just made your first chart using 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.

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.

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.

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.

Horizontal column chart with two series

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.

step2.zip

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.

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.

"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.

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

You can click to download and open it in 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.

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

fetch('//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('//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(function (response) { return response.text(); })

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

.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(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.

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.

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:

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.

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.

Let's take a look at this data file to get an idea of what's inside: //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.

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.

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.

Update the csvToSeries() function with the following code:

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:

{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.

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

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.

Update the csvToSeries() with the following code:

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.

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.

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.

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.

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

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:

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.

step3-b.zip

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.

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.

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.

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

step4-a.zip

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

Line chart showing filtered CSV data

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.

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:

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.

Line chart with title and annotation for attribution

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.

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: '%seriesName', 
Line chart using point labels instead of a legend

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.

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.

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.

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_tooltip: '%seriesName %yValue 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.

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: '%seriesName', defaultPoint_tooltip: '%seriesName %yValue years', xAxis_crosshair_enabled: true, series: series }); } 

Refresh the browser window once more.

Line chart with crosshairs and customized combined tooltips

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.

Du kan tilpasse og justere kartene ytterligere for å dekke dine spesifikke behov. Besøk JSCharting-opplæringsdelen for å lære mer om et bestemt emne, eller finn diagrammer som ligner på det du vil lage i eksempler, og kopier dem for å fortsette datavisualiseringsreisen.

Hvis du får problemer med å jobbe med JSCharting, kan du kontakte supportteamet. De hjelper deg gjerne eller hjelper deg med å løse eventuelle problemer du får.

step4-b.zip

Bonusutfordring

Vi brukte ikke alle dataene som er tilgjengelige i den CSV-filen. La oss eksperimentere med det for moro skyld og øving.

Lag dette diagrammet ved hjelp av det du har lært.

Challenge: Replicate this chart on your own

Denne zip-filen inneholder svaret:

step5-bonus.zip

Kan du tenke deg andre diagrammer du kan lage med disse dataene? Fortsett å eksperimentere og nyt hvert minutt av det!