Oral  Brekke

Oral Brekke

1669824924

Build Interactive JavaScript Charts and Graphs

Recently, we had the pleasure to participate in a machine-learning project that involved libraries like React and D3.js. Among many tasks, I developed a few d3 bar charts and line charts that helped to process the result of ML models like Naive Bayes.

In this article, I would like to present my progress with D3.js so far and show the basic usage of this javascript chart library through the simple example of a bar chart.

After reading this article, you’ll learn how to create D3.js charts like this easily.

What is D3.js?

D3.js is a data-driven JavaScript library for manipulating DOM elements.

“D3 helps you bring data to life using HTML, SVG, and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation.” – d3js.org

Why would You create charts with D3.js in the first place? Why not just display an image?

Well, charts are based on information coming from third-party resources which require dynamic visualization during render time. Also, SVG is a very powerful tool that fits well in this application case.

Let’s take a detour to see what benefits we can get from using SVG.

The benefits of SVG

SVG stands for Scalable Vector Graphics which is technically an XML-based markup language.

It is commonly used to draw vector graphics, specify lines and shapes or modify existing images. You can find the list of available elements here.

Pros:

  • Supported in all major browsers;
  • It has a DOM interface, requires no third-party lib;
  • Scalable, it can maintain high resolution;
  • Reduced size compared to other image formats.

Cons:

  • It can only display two-dimensional images;
  • Long learning curve;
  • Render may take a long with compute-intensive operations.

Getting started with D3.js

I picked bar charts to get started because it represents a low-complexity visual element while it teaches the basic application of D3.js itself. This should not deceive You, D3 provides a great set of tools to visualize data.

If you want to learn D3.js with Angular, you can refer here.

How to draw bar graphs with SVG?

SVG has a coordinate system that starts from the top left corner (0;0). The positive x-axis goes to the right, while the positive y-axis heads to the bottom. Thus, the height of the SVG has to be taken into consideration when it comes to calculating the y coordinate of an element.

bar2

That’s enough background check, let’s write some code!

Let’s take an example, I want to create a chart with 1000 pixels width and 600 pixels height.

<body>
	<svg />
</body>
<script>
    const margin = 60;
    const width = 1000 - 2 * margin;
    const height = 600 - 2 * margin;

    const svg = d3.select('svg');
</script>

In the code snippet above, I select the created <svg> element in the HTML file with d3 select. This selection method accepts all kinds of selector strings and returns the first matching element. Use selectAll them if You would like to get all of them.

I also define a margin value which gives a little extra padding to the chart. Padding can be applied with an <g> element translated by the desired value. From now on, I draw on this group to keep a healthy distance from any other contents of the page.

const chart = svg.append('g')
    .attr('transform', `translate(${margin}, ${margin})`);

Adding attributes to an element is as easy as calling the attr method. The method’s first parameter takes an attribute I want to apply to the selected DOM element. The second parameter is the value or a callback function that returns its value of it. The code above simply moves the start of the chart to the (60;60) position of the SVG.

Supported D3.js input formats

To start drawing, I need to define the data source I’m working from. For this tutorial, I use a plain JavaScript array that holds objects with the name of the languages and their percentage rates but it’s important to mention that D3.js supports multiple data formats.

The library has built-in functionality to load from XMLHttpRequest, .csv files, text files etc. Each of these sources may contain data that D3.js can use, the only important thing is to construct an array out of them. Note that, from version 5.0 the library uses promises instead of callbacks for loading data which is a non-backward compatible change.

Scaling, Axes

Let’s go on with the axes of the chart. In order to draw the y-axis, I need to set the lowest and the highest value limit which in this case are 0 and 100.

I’m working with percentages in this tutorial, but there are utility functions for data types other than numbers which I will explain later.

I have to split the height of the chart between these two values into equal parts. For this, I create something that is called a scaling function.

const yScale = d3.scaleLinear()
    .range([height, 0])
    .domain([0, 100]);

The linear scale is the most commonly known scaling type. It converts a continuous input domain into a continuous output range. Notice the range and domain method. The first one takes the length that should be divided between the limits of the domain values.

Remember, the SVG coordinate system starts from the top left corner that’s why the range takes the height as the first parameter and not zero.

Creating an axis on the left is as simple as adding another group and calling d3s axisLeft the method with the scaling function as a parameter.

chart.append('g')
    .call(d3.axisLeft(yScale));

Now, continue with the x-axis.

const xScale = d3.scaleBand()
    .range([0, width])
    .domain(sample.map((s) => s.language))
    .padding(0.2)

chart.append('g')
    .attr('transform', `translate(0, ${height})`)
    .call(d3.axisBottom(xScale));

bar3

Be aware that I use scaleBand for the x-axis which helps to split the range into bands and compute the coordinates and widths of the bars with additional padding.

D3.js is also capable of handling date types among many others. scaleTime is really similar to scaleLinear except the domain is here an array of dates.

Bar drawing in D3.js

Think about what kind of input we need to draw the bars. They each represent a value that is illustrated with simple shapes, specifically rectangles. In the next code snippet, I append them to the created group element.

chart.selectAll()
    .data(goals)
    .enter()
    .append('rect')
    .attr('x', (s) => xScale(s.language))
    .attr('y', (s) => yScale(s.value))
    .attr('height', (s) => height - yScale(s.value))
    .attr('width', xScale.bandwidth())

First, I selectAll elements on the chart which returns an empty result set. Then, data the function tells how many elements the DOM should be updated with based on the array length. enter identifies elements that are missing if the data input is longer than the selection. This returns a new selection representing the elements that need to be added. Usually, this is followed by a append which adds elements to the DOM.

Basically, I tell D3.js to append a rectangle for every member of the array.

Now, this only adds rectangles on top of each other which have no height or width. These two attributes have to be calculated and that’s where the scaling functions come in handy again.

See, I add the coordinates of the rectangles with the attr call. The second parameter can be a callback which takes 3 parameters: the actual member of the input data, its index of it, and the whole input.

.attr(’x’, (actual, index, array) =>
    xScale(actual.value))

The scaling function returns the coordinate for a given domain value. Calculating the coordinates is a piece of cake, the trick is with the height of the bar. The computed y coordinate has to be subtracted from the height of the chart to get the correct representation of the value as a column.

I define the width of the rectangles with the scaling function as well. scaleBand has a bandwidth the function which returns the computed width for one element based on the set padding.

D3.js Grid System

I want to highlight the values by adding grid lines in the background.

Go ahead, and experiment with both vertical and horizontal lines but my advice is to display only one of them. Excessive lines can be distracting. This code snippet presents how to add both solutions.

chart.append('g')
    .attr('class', 'grid')
    .attr('transform', `translate(0, ${height})`)
    .call(d3.axisBottom()
        .scale(xScale)
        .tickSize(-height, 0, 0)
        .tickFormat(''))

chart.append('g')
    .attr('class', 'grid')
    .call(d3.axisLeft()
        .scale(yScale)
        .tickSize(-width, 0, 0)
        .tickFormat(''))

bar1

I prefer the vertical grid lines in this case because they lead the eyes and keep the overall picture plain and simple.

Labels in D3.js

I also want to make the diagram more comprehensive by adding some textual guidance. Let’s give a name to the chart and add labels for the axes.

bar4

Texts are SVG elements that can be appended to the SVG or groups. They can be positioned with x and y coordinates while text alignment is done with the text-anchor attribute. To add the label itself, just call the text a method on the text element.

svg.append('text')
    .attr('x', -(height / 2) - margin)
    .attr('y', margin / 2.4)
    .attr('transform', 'rotate(-90)')
    .attr('text-anchor', 'middle')
    .text('Love meter (%)')

svg.append('text')
    .attr('x', width / 2 + margin)
    .attr('y', 40)
    .attr('text-anchor', 'middle')
    .text('Most loved programming languages in 2018')

Interactivity with Javascript and D3

We got quite an informative chart but still, there are possibilities to transform it into an interactive bar chart!

In the next code block, I show You how to add event listeners to SVG elements.

svgElement
    .on('mouseenter', function (actual, i) {
        d3.select(this).attr(‘opacity’, 0.5)
    })
    .on('mouseleave’, function (actual, i) {
        d3.select(this).attr(‘opacity’, 1)
    })

Note that I use a function expression instead of an arrow function because I access the element via this keyword.

I set the opacity of the selected SVG element to half of the original value on mouse hover and reset it when the cursor leaves the area.

You could also get the mouse coordinates with d3.mouse. It returns an array with the x and y coordinates. This way, displaying a tooltip at the tip of the cursor would be no problem at all.

Wrapping up our D3.js Bar Chart

D3.js is an amazing library for DOM manipulation and for building javascript graphs and line charts. The depth of it hides countlessly hidden (actually not hidden, it is really well documented) treasures that wait for discovery. This writing covers only fragments of its toolset that help to create a not-so-mediocre bar chart.

Go on, explore it, use it and create spectacular JavaScript graphs & visualizations!

By the way, here’s the link to the source code.

Have You created something cool with D3.js? Share with us! Drop a comment if You have any questions or would like another JavaScript chart tutorial!

Thanks for reading 🙂

Original article source at: https://blog.knoldus.com/

#javascript #charts #graphs 

What is GEEK

Buddha Community

Build Interactive JavaScript Charts and Graphs
Oral  Brekke

Oral Brekke

1669824924

Build Interactive JavaScript Charts and Graphs

Recently, we had the pleasure to participate in a machine-learning project that involved libraries like React and D3.js. Among many tasks, I developed a few d3 bar charts and line charts that helped to process the result of ML models like Naive Bayes.

In this article, I would like to present my progress with D3.js so far and show the basic usage of this javascript chart library through the simple example of a bar chart.

After reading this article, you’ll learn how to create D3.js charts like this easily.

What is D3.js?

D3.js is a data-driven JavaScript library for manipulating DOM elements.

“D3 helps you bring data to life using HTML, SVG, and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation.” – d3js.org

Why would You create charts with D3.js in the first place? Why not just display an image?

Well, charts are based on information coming from third-party resources which require dynamic visualization during render time. Also, SVG is a very powerful tool that fits well in this application case.

Let’s take a detour to see what benefits we can get from using SVG.

The benefits of SVG

SVG stands for Scalable Vector Graphics which is technically an XML-based markup language.

It is commonly used to draw vector graphics, specify lines and shapes or modify existing images. You can find the list of available elements here.

Pros:

  • Supported in all major browsers;
  • It has a DOM interface, requires no third-party lib;
  • Scalable, it can maintain high resolution;
  • Reduced size compared to other image formats.

Cons:

  • It can only display two-dimensional images;
  • Long learning curve;
  • Render may take a long with compute-intensive operations.

Getting started with D3.js

I picked bar charts to get started because it represents a low-complexity visual element while it teaches the basic application of D3.js itself. This should not deceive You, D3 provides a great set of tools to visualize data.

If you want to learn D3.js with Angular, you can refer here.

How to draw bar graphs with SVG?

SVG has a coordinate system that starts from the top left corner (0;0). The positive x-axis goes to the right, while the positive y-axis heads to the bottom. Thus, the height of the SVG has to be taken into consideration when it comes to calculating the y coordinate of an element.

bar2

That’s enough background check, let’s write some code!

Let’s take an example, I want to create a chart with 1000 pixels width and 600 pixels height.

<body>
	<svg />
</body>
<script>
    const margin = 60;
    const width = 1000 - 2 * margin;
    const height = 600 - 2 * margin;

    const svg = d3.select('svg');
</script>

In the code snippet above, I select the created <svg> element in the HTML file with d3 select. This selection method accepts all kinds of selector strings and returns the first matching element. Use selectAll them if You would like to get all of them.

I also define a margin value which gives a little extra padding to the chart. Padding can be applied with an <g> element translated by the desired value. From now on, I draw on this group to keep a healthy distance from any other contents of the page.

const chart = svg.append('g')
    .attr('transform', `translate(${margin}, ${margin})`);

Adding attributes to an element is as easy as calling the attr method. The method’s first parameter takes an attribute I want to apply to the selected DOM element. The second parameter is the value or a callback function that returns its value of it. The code above simply moves the start of the chart to the (60;60) position of the SVG.

Supported D3.js input formats

To start drawing, I need to define the data source I’m working from. For this tutorial, I use a plain JavaScript array that holds objects with the name of the languages and their percentage rates but it’s important to mention that D3.js supports multiple data formats.

The library has built-in functionality to load from XMLHttpRequest, .csv files, text files etc. Each of these sources may contain data that D3.js can use, the only important thing is to construct an array out of them. Note that, from version 5.0 the library uses promises instead of callbacks for loading data which is a non-backward compatible change.

Scaling, Axes

Let’s go on with the axes of the chart. In order to draw the y-axis, I need to set the lowest and the highest value limit which in this case are 0 and 100.

I’m working with percentages in this tutorial, but there are utility functions for data types other than numbers which I will explain later.

I have to split the height of the chart between these two values into equal parts. For this, I create something that is called a scaling function.

const yScale = d3.scaleLinear()
    .range([height, 0])
    .domain([0, 100]);

The linear scale is the most commonly known scaling type. It converts a continuous input domain into a continuous output range. Notice the range and domain method. The first one takes the length that should be divided between the limits of the domain values.

Remember, the SVG coordinate system starts from the top left corner that’s why the range takes the height as the first parameter and not zero.

Creating an axis on the left is as simple as adding another group and calling d3s axisLeft the method with the scaling function as a parameter.

chart.append('g')
    .call(d3.axisLeft(yScale));

Now, continue with the x-axis.

const xScale = d3.scaleBand()
    .range([0, width])
    .domain(sample.map((s) => s.language))
    .padding(0.2)

chart.append('g')
    .attr('transform', `translate(0, ${height})`)
    .call(d3.axisBottom(xScale));

bar3

Be aware that I use scaleBand for the x-axis which helps to split the range into bands and compute the coordinates and widths of the bars with additional padding.

D3.js is also capable of handling date types among many others. scaleTime is really similar to scaleLinear except the domain is here an array of dates.

Bar drawing in D3.js

Think about what kind of input we need to draw the bars. They each represent a value that is illustrated with simple shapes, specifically rectangles. In the next code snippet, I append them to the created group element.

chart.selectAll()
    .data(goals)
    .enter()
    .append('rect')
    .attr('x', (s) => xScale(s.language))
    .attr('y', (s) => yScale(s.value))
    .attr('height', (s) => height - yScale(s.value))
    .attr('width', xScale.bandwidth())

First, I selectAll elements on the chart which returns an empty result set. Then, data the function tells how many elements the DOM should be updated with based on the array length. enter identifies elements that are missing if the data input is longer than the selection. This returns a new selection representing the elements that need to be added. Usually, this is followed by a append which adds elements to the DOM.

Basically, I tell D3.js to append a rectangle for every member of the array.

Now, this only adds rectangles on top of each other which have no height or width. These two attributes have to be calculated and that’s where the scaling functions come in handy again.

See, I add the coordinates of the rectangles with the attr call. The second parameter can be a callback which takes 3 parameters: the actual member of the input data, its index of it, and the whole input.

.attr(’x’, (actual, index, array) =>
    xScale(actual.value))

The scaling function returns the coordinate for a given domain value. Calculating the coordinates is a piece of cake, the trick is with the height of the bar. The computed y coordinate has to be subtracted from the height of the chart to get the correct representation of the value as a column.

I define the width of the rectangles with the scaling function as well. scaleBand has a bandwidth the function which returns the computed width for one element based on the set padding.

D3.js Grid System

I want to highlight the values by adding grid lines in the background.

Go ahead, and experiment with both vertical and horizontal lines but my advice is to display only one of them. Excessive lines can be distracting. This code snippet presents how to add both solutions.

chart.append('g')
    .attr('class', 'grid')
    .attr('transform', `translate(0, ${height})`)
    .call(d3.axisBottom()
        .scale(xScale)
        .tickSize(-height, 0, 0)
        .tickFormat(''))

chart.append('g')
    .attr('class', 'grid')
    .call(d3.axisLeft()
        .scale(yScale)
        .tickSize(-width, 0, 0)
        .tickFormat(''))

bar1

I prefer the vertical grid lines in this case because they lead the eyes and keep the overall picture plain and simple.

Labels in D3.js

I also want to make the diagram more comprehensive by adding some textual guidance. Let’s give a name to the chart and add labels for the axes.

bar4

Texts are SVG elements that can be appended to the SVG or groups. They can be positioned with x and y coordinates while text alignment is done with the text-anchor attribute. To add the label itself, just call the text a method on the text element.

svg.append('text')
    .attr('x', -(height / 2) - margin)
    .attr('y', margin / 2.4)
    .attr('transform', 'rotate(-90)')
    .attr('text-anchor', 'middle')
    .text('Love meter (%)')

svg.append('text')
    .attr('x', width / 2 + margin)
    .attr('y', 40)
    .attr('text-anchor', 'middle')
    .text('Most loved programming languages in 2018')

Interactivity with Javascript and D3

We got quite an informative chart but still, there are possibilities to transform it into an interactive bar chart!

In the next code block, I show You how to add event listeners to SVG elements.

svgElement
    .on('mouseenter', function (actual, i) {
        d3.select(this).attr(‘opacity’, 0.5)
    })
    .on('mouseleave’, function (actual, i) {
        d3.select(this).attr(‘opacity’, 1)
    })

Note that I use a function expression instead of an arrow function because I access the element via this keyword.

I set the opacity of the selected SVG element to half of the original value on mouse hover and reset it when the cursor leaves the area.

You could also get the mouse coordinates with d3.mouse. It returns an array with the x and y coordinates. This way, displaying a tooltip at the tip of the cursor would be no problem at all.

Wrapping up our D3.js Bar Chart

D3.js is an amazing library for DOM manipulation and for building javascript graphs and line charts. The depth of it hides countlessly hidden (actually not hidden, it is really well documented) treasures that wait for discovery. This writing covers only fragments of its toolset that help to create a not-so-mediocre bar chart.

Go on, explore it, use it and create spectacular JavaScript graphs & visualizations!

By the way, here’s the link to the source code.

Have You created something cool with D3.js? Share with us! Drop a comment if You have any questions or would like another JavaScript chart tutorial!

Thanks for reading 🙂

Original article source at: https://blog.knoldus.com/

#javascript #charts #graphs 

Reid  Rohan

Reid Rohan

1656899776

Graph-scroll: Simple Scrolling Events for D3 Graphs

graph-scroll.js

Simple scrolling events for d3 graphs. Based on stack

Demo/Documentation

graph-scroll takes a selection of explanatory text sections and dispatches active events as different sections are scrolled into to view. These active events can be used to update a chart's state.

d3.graphScroll()
    .sections(d3.selectAll('#sections > div'))
    .on('active', function(i){ console.log(i + 'th section active') })

The top most element scrolled fully into view is classed graph-scroll-active. This makes it easy to highlight the active section with css:

#sections > div{
	opacity: .3
} 

#sections div.graph-scroll-active{
	opacity: 1;
}

To support headers and intro images/text, we use a container element containing the explanatory text and graph.

<h1>Page Title</div>
<div id='container'>
  <div id='graph'></div>
  <div id='sections'>
    <div>Section 0</div>
    <div>Section 1</div>
    <div>Section 2</div>
  </div>
</div>
<h1>Footer</h1>

If these elements are passed to graphScroll as selections with container and graph, every element in the graph selection will be classed graph-scroll-graph if the top of the container is out of view.

d3.graphScroll()
	.graph(d3.selectAll('#graph'))
	.container(d3.select('#container'))
  .sections(d3.selectAll('#sections > div'))
  .on('active', function(i){ console.log(i + 'th section active') })

When the graph starts to scroll out of view, position: sticky keeps the graph element stuck to the top of the page while the text scrolls by.

#container{
  position: relative;
}

#sections{
  width: 340px;
}

#graph{
  margin-left: 40px;
  width: 500px;
  position: sticky;
  top: 0px;
  float: right;
}

On mobile centering the graph and sections while adding a some padding for the first slide is a good option:

@media (max-width: 925px)  {
  #graph{
    width: 100%;
    margin-left: 0px;
    float: none;
  }

  #sections{
    position: relative;
    margin: 0px auto;
    padding-top: 400px;
  }
}

Adjust the amount of pixels before a new section is triggered is also helpful on mobile (Defaults to 200 pixels):

graphScroll.offset(300)

To update or replace a graphScroll instance, pass a string to eventId to remove the old event listeners:

graphScroll.eventId('uniqueId1')

Author: 1wheel
Source Code: https://github.com/1wheel/graph-scroll 
License: MIT license

#javascript #d3 #graph 

Arun A

1623648922

ASP.NET Core Charts - Rich & Interactive Graphs with Real-time data

Overview
The ASP.NET Core Chart is a well-crafted charting component to visualize data. It contains a rich UI gallery of 30+ charts and graphs, ranging from line to financial that cater to all charting scenarios. Its high performance helps render large amounts of data quickly. It also comes with features such as zooming, panning, tooltip, crosshair, trackball, highlight, and selection.

Why choose Syncfusion ASP.NET Core charts?

30+ Chart types
Ranging from simple day-to-day charts like line charts, bar charts, area charts to complex financial charts that are highly customizable.

Chart animation
Charts for ASP.NET Core provides fluid animation to represent data with smooth transitions.

Performance
Well thought out efforts, and focuses mainly on fast paced performance to render 100k data in less than a second.

SVG rendering
Vector based clean and crisp rendering for all your responsive and scaling needs.

Data Editing
Provides drag and drop support to the rendered points. Data editing allows you to manipulate the data on a chart.

Trendlines
Shows the price direction and movement speed. Trendlines can be generated for Cartesian type series (Line, Column, Scatter, Area, Candle, HiLo, etc.) except bar. More than one trendline can be added to a series.

Globalization and localization
Enables users from different locales to use them by formatting dates, currency, and numbering to suit preferences.

Exporting
Export charts to PDF documents or as image formats such as SVG, PNG and JPEG.
https://www.syncfusion.com/aspnet-core-ui-controls/charts

#asp.net core charts #chart types #charts #web-development #graphs

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Einar  Hintz

Einar Hintz

1593235440

Visualizing data with NGX-Charts in Angular

Data Science, Data Analytics, Big Data, these are the buzz words of today’s world. A huge amount of data is being generated and analyzed every day. So communicating the insights from that data becomes crucial. Charts help visualize the data and communicate the result of the analysis with charts, it becomes easy to understand the data.

There are a lot of libraries for angular that can be used to build charts. In this blog, we will look at one such library, NGX-Charts. We will see how to use it in angular and how to build data visualizations.

What we will cover:

  1. Installing ngx-chart.

  2. Building a vertical bar graph.

  3. Building a pie chart.

  4. Building an advanced pie chart.

A brief introduction about NGX-Charts

NGX-Chart charting framework for angular2+. It’s open-source and maintained by Swimlane.

NGX-Charts does not merely wrap d3, nor any other chart engine for that matter. It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functions, scales, axis and shape generators, etc. By having Angular do all of the renderings it opens us up to endless possibilities the Angular platform provides such as AoT, Universal, etc.

NGX-Charts supports various chart types like bar charts, line charts, area charts, pie charts, bubble charts, doughnut charts, gauge charts, heatmap, treemap, and number cards.

Installation and Setup

1. Install the ngx-chart package in your angular app.

npm install @swimlane/ngx-charts --save

2. At the time of installing or when you serve your application is you get an error:

ERROR in The target entry-point "@swimlane/ngx-charts" has missing dependencies: - @angular/cdk/portal

You also need to install angular/cdk

npm install @angular/cdk --save

3. Import NgxChartsModule from ‘ngx-charts’ in AppModule

4. NgxChartModule also requires BrowserAnimationModule. Import is inAppModule.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NgxChartsModule }from '@swimlane/ngx-charts';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    NgxChartsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Amazing! Now we can start using ngx-chart component and build the graph we want.

In the AppComponent we will provide data that the chart will represent. It’s a sample data for vehicles on the road survey.

#angular #angular 6 #scala #angular #angular 9 #bar chart #charting #charts #d3 charts #data visualisation #ngx #ngx charts #pie