Angular ngx-charts options for customizing the Legend?

ngx-charts custom legend
ngx-charts-legend
ngx charts legend horizontal
ngx charts change legend width
ngx-charts customization
ngx-charts legend click
ngx-charts legend css
ngx pie chart legend width

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:

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

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>

Angular NGX-Charts: using a custom legend, Component template and related functions: <div> <ngx-charts-pie-chart [scheme ]="colorScheme" [results]="chart.data"� <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

If you are looking for a pure CSS solution this should be good jumping off point. In my application, we have a half-screen sized chart where the legend was cutting off longer labels.

Using version 12.0.1. This is heavily dependent on the DOM structure so if something changes in future releases this may not work.

The parent container of the chart must have extra space in it or the legend will wrap below the chart. In this example, assume the parent container width is > 800px, and the chart is using a fixed view of width 620px. You will have to turn off view encapsulation for your component as well.

In component file:

@Component({
   ...
   encapsulation: ViewEncapsulation.None
})

In CSS file:

/* Makes the chart container expand to the full width of the parent container*/
.ngx-charts-outer {
    width: 100% !important;
}

/* Sets the legend width to auto expand to fit labels, but caps at 200px */
.chart-legend > div {
    width: auto !important;
    max-width: 200px;
}

/* Some extra space is needed to offset the way the labels display */
.legend-labels {
    width: calc(100% + 10px) !important;
}

/* Wrap the label text if it ends up being longer than the max width */
.legend-label-text {
    white-space: normal !important;
    width: 100% !important;
}

Angular ngx-charts options for customizing the Legend?, 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,� Angular ngx-charts options for customizing the Legend? 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'.

If anyone was helped by @Maya Sol but was wondering the same thing as @Ollie, here's how you can do it. I'm adding an answer since I don't have enough reputation to add comments.

Modify the the legendLabelActivate function to do the following:

public legendLabelActivate(item: any): void {
    // The if statement is here so both legend  
    // and chart element mouse over events will work.
    if (item.value === undefined) {
        this.activeEntries = [item];
    } else {
        this.activeEntries = [{ name: item.value.name }];
    }
}

Then, using the example html from @Maya Sol ... in the ngx-charts-line-chart and ngx-charts-legend do the following:

<div fxLayout="row">
    <div fxFlex="50%">
        <ngx-charts-line-chart [legend]="false"
                               [activeEntries]="activeEntries" 
                               (activate)="legendLabelActivate($event)" 
                               (deactivate)="legendLabelDeactivate($event)"
                               [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"
                           [activeEntries]="activeEntries" 
                           (labelActivate)="legendLabelActivate($event)" 
                           (labelDeactivate)="legendLabelDeactivate($event)">
        </ngx-charts-legend>
    </div>
</div>

Angular ngx-charts options for customizing the Legend?, 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,� Ngx-charts is a charting framework for Angular which wraps the D3 JavaScript library and uses Angular to render and animate SVG elements. It is one of the most popular frameworks for Angular

swimlane/ngx-charts, Hi, any pointer why my legends are truncating for the Advanced pie chart. Creating a custom chart extending the BaseChartComponent (for example, in a combo I'm trying to import the @swimlane/ngx-charts at the latest version into my @angular 4 app. You must set responseType: 'json' on your http request option. ngx-charts is unique because we don't 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.

Legend Positions � Issue #135 � swimlane/ngx-charts � GitHub, Add ability to position the legend top|right|bottom|left. Change ngx-charts-bar- horizontal legend position #372 I have two diagrams in two separate angular components and I need to visualize the diagrams as in the image each col div, the pie-chart component with custom configuration per chart. <ngx-charts-legend [data]="domain" [colors]="colors"></ngx-charts-legend> instead of letting the chart do it for me. However, the styling does not take effect because the css expects it to be wrapped in .chart-legend. I easily work around by surrounding like so:

Features - ngx-charts, Customization. Autoscaling. Timeline Filtering. Line Interpolation. Configurable Axis Labels. Legends (Labels & Gradient). This returns the legend items from the Chart as-is. You have the option of customizing that return value. In my case, I needed to add the value of the "slope" of the line to each legend item, which is not provided by Chart.js.

Comments
  • Did you manage to customize the legend? I'm also struggling with it.
  • nope, no chance...
  • your suggestion almost works, needs bit improvement: public colorScheme = ['#0000FF', '#008000']; needs to be: public colorScheme = {domain: ['#0000FF', '#008000']};
  • Is there a way to highlight the relevant item in the legend when a point in that series is hovered over (kind of the reverse of what legendLabelActivate is doing)?
  • If you have console errors, probably you forgot to initialize something. e.g. public activeEntries: any[] = [];