Cómo hacer su primer gráfico de JavaScript con JSCharting

Cuando comienzas como desarrollador de JavaScript principiante, creo que es importante perseguir proyectos interesantes. De esa manera, puede asegurarse de divertirse mientras aprende, y es probable que encuentre un área de especialización que disfrute.

Como dicen, "si amas lo que haces, nunca trabajarás un día en tu vida" .

En este artículo, les presentaré la visualización de datos front-end, que es mi pasión personal. ¡Quizás también se convierta en tu pasión!

Los momentos más gratificantes para mí como desarrollador son cuando puedo ver o experimentar los resultados de lo que hice. Es muy satisfactorio crear un gráfico que revele información interesante sobre sus datos o una experiencia interactiva que ayude a explorar los detalles de un conjunto de datos único. Cuanto más significativo sea el resultado, más gratificante se siente.

Sin embargo, me he dado cuenta de que la cantidad de trabajo que pones en un proyecto no se correlaciona necesariamente con la sensación de logro; a veces se siente genial incluso cuando era relativamente fácil.

Con el tiempo, encontrará herramientas que lo ayudarán a ser más eficiente y, a veces, moverá montañas con poco esfuerzo. Hay muchas bibliotecas de gráficos y herramientas disponibles en el campo de visualización de datos. Con las herramientas adecuadas, creará nuevos gráficos con poco esfuerzo, independientemente del tipo de gráfico que necesite. Personalmente, creo que datavis genera una gran recompensa por su inversión de tiempo y esfuerzo.

En este tutorial, utilizará una serie de herramientas para obtener datos a través de Internet, procesarlos y dibujar un hermoso gráfico que se puede ver en cualquier navegador moderno. Puede hacer clic en los enlaces a continuación para descargar un código de ejemplo para cada paso individualmente, verlos todos en GitHub o descargar todos los pasos a la vez aquí: all-steps.zip.

El resultado

Al final de este tutorial, creará este gráfico interactivo basado en datos. Aprenderá cómo obtener datos a través de Internet, procesarlos y hacer un gráfico con esos datos. También podrá crear sus propios gráficos desde cero.

Gráfico de líneas de JavaScript interactivo

Después de procesar los datos y graficarlos, también aprenderá cómo realizar ajustes en el gráfico, incluida la modificación de la leyenda predeterminada, habilitar la retícula del eje x con información sobre herramientas y aplicar anotaciones de texto para agregar contexto y otra información al gráfico.

Las herramientas

Para comenzar, use un navegador de Internet como el que probablemente esté usando para leer este artículo. Recomiendo Chrome ya que ofrece una gran experiencia y herramientas integradas para desarrolladores.

A continuación, necesitará un editor de texto. Algo tan simple como el bloc de notas funcionará. Pero, sugiero usar un editor de código más avanzado como VS Code, ya que este es un entorno con el que pasará mucho tiempo. Le brindará una experiencia de codificación más conveniente y agradable, y hará que escribir HTML5, CSS y JavaScript sea más fácil para la vista. Lo más importante es que si olvidas una cita o una coma en algún lugar, un editor de código puede ayudarte a encontrar el error.

Este artículo puede ayudarlo a elegir el mejor editor de código JavaScript para el desarrollo web.

Utilizará la biblioteca de gráficos JSCharting para dibujar y agregar automáticamente funciones interactivas para este gráfico. No se requerirán otras bibliotecas de JavaScript como jQuery o plataformas de front-end, incluidas React y Angular (comúnmente utilizadas para proyectos de sitios web).

¿Por qué JSCharting?

JSCharting es una biblioteca de gráficos de JavaScript que puede dibujar muchos tipos diferentes de gráficos usando SVG. Es fácil de usar y comenzar, por lo que es una buena opción para este tutorial. La API (Interfaz de programación de aplicaciones, también conocida como las opciones y configuraciones necesarias para crear gráficos) simplifica las cosas difíciles y es una buena opción cuando se experimenta con visualizaciones de datos.

Puede utilizar JSCharting de forma gratuita para uso personal y comercial con la marca incluida.

Puede crear gráficos receptivos con JSCharting mediante un par de sencillos pasos:

  • Defina una etiqueta en el archivo HTML con una identificación única.
  • Proporcione esta identificación, datos y cualquier otra opción cuando llame JSC.Chart()al archivo JavaScript.

Eso es. JSC dibujará un gráfico de aspecto profesional que rellene esta etiqueta div con elementos visuales SVG. El gráfico será receptivo e interactivo sin ningún esfuerzo adicional.

Los datos

Utilizará un archivo de datos proporcionado por el NCHS (Centro Nacional de Estadísticas de Salud) que enumera la esperanza de vida histórica de hombres y mujeres en los EE. UU.

Puede encontrarlo aquí: //data.cdc.gov/resource/w9j2-ggv5.csv.

Este archivo CSV contiene datos que clasifican las expectativas de vida por año, raza y sexo. Utilizará algunos de estos datos para trazar una línea de tendencia masculina / femenina simple durante los últimos 100 años.

CSV (valores separados por comas) es un gran formato para transmitir datos a través de Internet. Es compacto, legible por humanos y puedes abrirlo directamente en Excel, lo cual también es bueno.

Así que sin más preámbulos, comencemos.

Paso 1: agregue un gráfico en blanco

El primer archivo zip contiene un punto de inicio en blanco que puede completar a medida que avanzamos. Si se pierde o se confunde, o desea avanzar, el archivo zip al final o a lo largo de cada sección lo pondrá al día.  

Si desea descargar todos los archivos a la vez, consulte all-steps.zipen su lugar .

step1-a.zip

Este archivo zip contiene los siguientes archivos.

  • index.html
  • js/index.js

El .htmlarchivo está vacío excepto por algún código estándar que lo convierte en un archivo válido y el .jsarchivo está completamente en blanco.

El primer paso es agregar algunos scripts al archivo de la página web HTML. Normalmente, la gente sugiere agregar etiquetas dentro de las etiquetas. Sin embargo, para los scripts que afectan el contenido HTML, a menudo es mejor agregarlos después de la etiqueta de cierre .

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.

Puede personalizar y ajustar los gráficos aún más para satisfacer sus necesidades específicas. Visite la sección de tutoriales de JSCharting para obtener más información sobre un tema específico, o busque gráficos similares a los que desea hacer en la galería de ejemplos y cópielos para continuar su viaje de visualización de datos.

Si tiene problemas al trabajar con JSCharting, no dude en ponerse en contacto con el equipo de soporte. Estarán encantados de guiarle o ayudarlo a resolver cualquier problema que pueda encontrar.

step4-b.zip

Desafío de bonificación

No utilizamos todos los datos disponibles en ese archivo CSV. Experimentemos con él para divertirnos y practicar.

Crea este cuadro usando lo que has aprendido.

Challenge: Replicate this chart on your own

Este archivo zip contiene la respuesta:

step5-bonus.zip

¿Puedes pensar en otros gráficos que puedas hacer con estos datos? ¡Sigue experimentando y disfruta cada minuto!