Skip to content

Instantly share code, notes, and snippets.

@gabrielloye
Last active January 25, 2024 06:16
Show Gist options
  • Save gabrielloye/67921cda6139ba1806920da2a7e2fcb2 to your computer and use it in GitHub Desktop.
Save gabrielloye/67921cda6139ba1806920da2a7e2fcb2 to your computer and use it in GitHub Desktop.

ngx-charts: Custom Bar/Line Combo Chart Tutorial


I've been using ngx-charts when building my Angular apps and its definitely one of the best free charting frameworks available for Angular (that I've tried at least). However, one thing I noticed is the lack of documentation or guides when it comes to creating or even using custom charts. Therefore I decided to create a simple walkthrough on how to use the bar/line combo-chart avaiable as one of their demos.

Walkthrough

Source Code

StackBlitz Link: You can refer to this link to see the final product/overview of how to use the custom chart in your project.

Ensure that you have swimlane/ngx-charts installed as a dependency
npm i @swimlane/ngx-charts --save

Creating and copying components

  • Create a folder named combo-charts that will store the components of the custom chart (which we will create next)
    • This folder can be created in a shared folder for your project or within other folders that you are going to use the component in
    • In the example, I just created it in the main app folder
  • From https://github.com/swimlane/ngx-charts/tree/master/demo/combo-chart, create and copy the exact components into the combo-charts folder which we have just created above. Your folder directory will look like this:\
combo-chart\
 └─ combo-chart.component.scss
 └─ combo-chart.component.ts
 └─ combo-series-vertical.component.ts
 └─ index.ts

Editing components

You'll notice that some of the imports in the code you've just copied are relative and do not exist. Its time to fix that

combo-chart.component.ts
  • In combo-chart.component.ts you'll see the following import:
import {
  NgxChartsModule, BaseChartComponent, LineComponent, LineSeriesComponent,
  calculateViewDimensions, ViewDimensions, ColorHelper
 } from '../../src';
  • Change the '../../src' to '@swimlane/ngx-charts'
combo-series-vertical.component.ts
  • In combo-series-vertical.component.ts you'll see the following import:
import { formatLabel } from '../../src/common/label.helper';
  • Similarly, change the '../../src/common/label.helper' to '@swimlane/ngx-charts'

These are the only changes we'll make to the custom components. You can leave the index.ts and combo-chart.component.scss as it is

Declaring Components and Imports

Next, We'll update our app.module.ts or feature modules and declare the components we have just created

  • First, ensure that you imported the NgxChartsModule and BrowserAnimationsModule
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgxChartsModule } from '@swimlane/ngx-charts';
.
.
imports: [
.
BrowserAnimationsModule
NgxChartsModule
.
  • Import the custom components using the relative file path to the combo-charts folder that we have just created in the earlier step and add the components to your declarations
.
import { ComboChartComponent, ComboSeriesVerticalComponent } from './combo-chart';
.
.
declarations: [
.
.
ComboChartComponent, ComboSeriesVerticalComponent],
.

Including the Custom Component

  • In the component that you intend to add the combo chart to, add the following code to the template or .html file
<combo-chart-component
[view]="view"
[scheme]="comboBarScheme"
[colorSchemeLine]="lineChartScheme"
[results]="barChart"
[animations]="animations"
[lineChart]="lineChartSeries"
[yAxisTickFormatting]="yLeftTickFormat"
[yLeftAxisScaleFactor]="yLeftAxisScale"
[yRightAxisScaleFactor]="yRightAxisScale"
[yRightAxisTickFormatting]="yRightTickFormat"
[gradient]="gradient"
[xAxis]="showXAxis"
[yAxis]="showYAxis"
[legend]="showLegend"
[legendTitle]="legendTitle"
[legendPosition]="legendPosition"
[showGridLines]="showGridLines"
[showXAxisLabel]="showXAxisLabel"
[showYAxisLabel]="showYAxisLabel"
[showRightYAxisLabel]="showYAxisLabel"
[xAxisLabel]="xAxisLabel"
[yAxisLabel]="yAxisLabel"
[yAxisLabelRight]="yAxisLabelRight">
</combo-chart-component>
  • In the .ts file of the component, you can define the variables for the properties and data, for example:
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  showXAxis = true;
  showYAxis = true;
  gradient = false;
  showLegend = true;
  legendTitle = 'Legend';
  legendPosition = 'right';
  showXAxisLabel = true;
  xAxisLabel = 'Country';
  showYAxisLabel = true;
  yAxisLabel = 'GDP Per Capita';
  showGridLines = true;
  innerPadding = '10%';
  animations: boolean = true;
  barChart: any[] = barChart;
  lineChartSeries: any[] = lineChartSeries;
  lineChartScheme = {
    name: 'coolthree',
    selectable: true,
    group: 'Ordinal',
    domain: ['#01579b', '#7aa3e5', '#a8385d', '#00bfa5']
  };

  comboBarScheme = {
    name: 'singleLightBlue',
    selectable: true,
    group: 'Ordinal',
    domain: ['#01579b']
  };

  showRightYAxisLabel: boolean = true;
  yAxisLabelRight: string = 'Utilization';
}
export let lineChartSeries = [
  {
    name: 'Tablets',
    series: [
          {
      name: 'USA',
      value: 50
    },
    .
    .
    .]
 export let barChart: any = [
  {
    name: 'USA',
    value: 50000
  },
  .
  .
  .]
  • Note: Not all the directives used in the example above have to be used in your code. You can refer to combo-chart.component.ts for the available inputs

Conclusion

After following the above steps, you should be able to see the combo-chart appear in the view. You can further customise the chart by adding to combo-chart.component.ts or combo-series-vertical.component.ts, which I will not cover here. I hope that this short and simple guide was helpful and clear in explaining how to start using custom charts from ngx-charts!

@chriszrc
Copy link

Thanks! Yeah, the process of creating a combo chart leaves much to be desired, I had hoped it was as simple as combining the templates, but all the low level mucking around is probably way too much work for most people.

@krinonnn
Copy link

krinonnn commented Apr 2, 2020

Hi @gabrielloye , is a combination of a stacked vertical bar and line possible with this approach? Cheers!

@rohan-patnaik
Copy link

In the creating and copying components tab the github link has changed.
https://github.com/swimlane/ngx-charts/tree/master/src/app/custom-charts/combo-chart
Please confirm and update ony our page.

@davidenriquez
Copy link

davidenriquez commented Jun 2, 2020

Hi guys,

Did anyone succeed to create a custom combo chart including other chart type than the demo one ?
And if yes, can you share a sample / repo of how did you manage to do it ?
Thanks

@travisredington
Copy link

Hey, I am using ngx-charts for a normalized bar chart. I am wondering if you know the formula they use to draw a 100% normalized horizontal bar chart? The reason is that i want to match the tick marks to exactly where each section ends and my math is a bit off from theirs. Any suggestions would be great, thanks! and thanks for posting this!

@EvaristoPerez
Copy link

Thank you @gabrielloye this are pretty net instructions to get this demo working! I will try to tweak it and have a line -stacked bar kind of combo and will share results if I get it done properly.

@EvaristoPerez
Copy link

EvaristoPerez commented Jan 2, 2021

In the creating and copying components tab the github link has changed.
https://github.com/swimlane/ngx-charts/tree/master/src/app/custom-charts/combo-chart
Please confirm and update ony our page.

Just tried the full process and you are correct, thankyou for pointing it out and let me add my couple of cents here. That link AND content changed, the combo-chart.component.ts used to include the template in -line. Now it has a separated HTML file. But it works the same by following @gabrielloye instructions.

@Pruthvi-017
Copy link

Pruthvi-017 commented Jan 27, 2021

Hi, @gabrielloye I have used the custom component above, everything came good. But I don't need the Y-Axis (0, 10, 20, 40...) values on the right side of the graph. I have checked but didn't get where to change. Can I know the change I have to make. Thanks

@tfiedler14
Copy link

tfiedler14 commented Jun 24, 2021

Hi @gabrielloye , I'm in the process of trying to create a custom chart. in the default set up of combo-chart-component, the template is used from 'ngx-charts-chart'. I am trying to add some customization to the bar chart being used, and would like to replace this with < ngx-charts-vertical-bar> so i can leverage properties like [showDataLabel]. This however prevents my chart from being displayed entirely. Do you have any insight as to what can be done to leverage other bar charts ngx offers? or if theres any known way of adding datalabels to the bar charts used already?

@f1shboy
Copy link

f1shboy commented Jul 27, 2021

I can't get some properties to work (results, view etc) unless I define them as Input fields inside the component.

I get the following error whenever I try to access any of these properties in a template without defining the as input fields first:

"Property view is not provided by any applicable directives nor by combo-chart-component element"

@RicardoVaranda
Copy link

@EvaristoPerez Could you please share a gist example of the Stacked bar & Line combo?

@adeline-chew-sp
Copy link

Hi here, interested in the stacked bar chart and line combo. Did anyone figure that out?

@maxiking445
Copy link

@chriszrc Late to the Party. But if someone also wants to Combine Bubblechart with a Linechart. Then here you go! Small Hacky Example but I hope it will help others to start with it :)

https://stackblitz.com/~/github.com/maxiking445/ngxBubbleLineComboCharts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment