图例位置
要将图例定位在图表下方,您可以使用legendPosition 输入:
<ngx-charts-chart [legendPosition]="'below'" [results]="chartData" [legend]="true"></ngx-charts-chart>
legendPosition 的唯一选项是“右”(默认)和“下方”。
重命名图例字段
似乎没有自定义图例字段的选项(高级饼图中有一个更可自定义的图例,但您的示例是其他类型的图表。)我认为最好的解决方法是传递字段标题完全按照您希望它们出现在图例中的方式输入您的 chartData 的 chartData[i].name 值,然后自定义您的工具提示以在此处显示不同的字段名称。
This answer gives an overview of how to customize tooltips. 从那里,我整理了一个带有折线图的示例,该示例看起来像默认工具提示,但字段名称不同:
<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>
更改图例宽度
图例宽度在其他图表扩展的ngx-charts-chart 组件中计算。它会将宽度设置为图表容器的大约 1/6 或 1/12,具体取决于您的数据类型。无法为此图例输入不同的宽度,因此您最简单的解决方案是在自动宽度不适合您时将legendPosition 设置为“低于”。
但是,您不需要使用图表中内置的图例!这是一个更复杂(但更精细)的替代方案:在图表中设置[legend]="false",然后在图表外添加一个新的ngx-charts-legend 组件。
您可以为此外部图例输入宽度和高度,也可以将其包装在一个 div 中,以便更快地处理大小调整。使用后一种方法时,我必须将图例的宽度设置为其容器的 100%。
要使此解决方案正常工作,您必须将外部图例激活事件绑定到图表,并设置一些图例输入属性 onInit。在包含图表的组件中,您需要这样的东西:
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);
}
然后我的模板(图表和图例各占一半宽度)看起来像:
<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>