Angular ngx-charts options for customizing the Legend?

MMM picture MMM · Aug 21, 2018 · Viewed 19.2k times · Source

I am currently using ngx-charts for Angular2, and I would like to customize some legends, e.g. place the legend below the chart, or rename the legend fields, or make the legend wider (parts of the text just gets cut off..) etc.

Are there any good options to customize the legend? Or is it generally not possible, or what is the best way to do it? Currently, my chart legends look like this:

enter image description here

Some legends are too wide, some are cut off, and I'd like to position the legend e.g below the chart...

Answer

Maya Sol picture Maya Sol · Jan 3, 2019

Legend Position

To position the legend below the chart, you can use the legendPosition input:

<ngx-charts-chart [legendPosition]="'below'" [results]="chartData" [legend]="true"></ngx-charts-chart>

The only options for legendPosition are 'right' (default) and 'below'.

Rename Legend Fields

There don't seem to be options for customizing the legend fields (there's a more customizable legend in the advanced pie chart, but your examples are other kinds of charts.) I think the best workaround would be to pass the field titles into your chartData's chartData[i].name values exactly as you want them to appear in the legend, and then customize your tooltip(s) to show a different field name there.

This answer gives an overview of how to customize tooltips. From there, I put together an example with a line chart that will look like the default tooltips except with a different field name:

<ngx-charts-line-chart [legendPosition]="'right'" [results]="chartData" [legend]="true">
    <ng-template #tooltipTemplate let-model="model">
        <xhtml:div class="area-tooltip-container">
            <span class="tooltip-label">{{ formatFieldName(model.series) }} • {{ formatXvalue(model.name) }}</span>
            <span class="tooltip-val">{{ formatYvalue(model.value) }}</span>
        </xhtml:div>
    </ng-template>
    <ng-template #seriesTooltipTemplate let-model="model">
        <xhtml:div class="area-tooltip-container">
            <xhtml:div *ngFor="let tooltipItem of model" class="tooltip-item">
                <span class="tooltip-item-color" [style.background-color]="tooltipItem.color">
                </span>
                {{ formatFieldName(tooltipItem.series) }}: {{ formatYvalue(tooltipItem.value) }}
            </xhtml:div>
        </xhtml:div>
    </ng-template>
</ngx-charts-line-chart>

Change Legend Width

The legend width is calculated in the ngx-charts-chart component that the other charts extend. It will set the width to about 1/6th or 1/12th of the chart container, depending on your data type. There is no way to input a different width to this legend, so your easiest solution is to set legendPosition to 'below' when the automatic width doesn't work for you.

However, you don't need to use the legend built into the chart! Here's a more complex (but more fine-tune-able) alternative: set [legend]="false" in your chart, and then add a new ngx-charts-legend component outside of the chart.

You can either input width and height to this external legend, or wrap it in a div that handles sizing more responsively. I had to set the legend's width to 100% of its container when using the latter method.

To get this solution working, you have to bind the external legend activation events to the chart, and set some of the legend input properties onInit. In the component that contains your chart, you'll need something like this:

import { ColorHelper } from '@swimlane/ngx-charts';
...
export class ChartContainerComponent implements OnInit {
    public activeEntries: any[];
    public chartData: { name: string, series: { name: string, value?: string | number }[] }[];
    public chartNames: string[];
    public colors: ColorHelper;
    public colorScheme = { domain: ['#0000FF', '#008000'] }; // Custom color scheme in hex

    public legendLabelActivate(item: any): void {
        this.activeEntries = [item];
    }

    public legendLabelDeactivate(item: any): void {
        this.activeEntries = [];
    }

    public ngOnInit(): void {
        // Get chartNames
        this.chartNames = this.chartData.map((d: any) => d.name);
        // Convert hex colors to ColorHelper for consumption by legend
        this.colors = new ColorHelper(this.colorScheme, 'ordinal', this.chartNames, this.colorScheme);
    }

Then my template (with chart and legend each taking half of the width) looks like:

<div fxLayout="row">
    <div fxFlex="50%">
        <ngx-charts-line-chart [legend]="false" [activeEntries]="activeEntries" [results]="chartData" [scheme]="colorScheme"></ngx-charts-line-chart>
    </div>
    <div fxFlex="50%">
        <ngx-charts-legend fxFlex="100%" class="chart-legend" [data]="chartNames" [title]="'Legend Title'" [colors]="colors" (labelActivate)="legendLabelActivate($event)" (labelDeactivate)="legendLabelDeactivate($event)"></ngx-charts-legend>
    </div>
</div>