Angular ngx-charts options for customizing the Leg

2020-08-10 09:24发布

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...

3条回答
啃猪蹄的小仙女
2楼-- · 2020-08-10 09:46

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;
}

查看更多
虎瘦雄心在
3楼-- · 2020-08-10 09:50

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>
查看更多
走好不送
4楼-- · 2020-08-10 09:58

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>
查看更多
登录 后发表回答