You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ngx-Charts:如何在归一化条形图的每个分段内添加文本

实现ngx-charts归一化水平条形图分段中间添加文本

要在ngx-charts的归一化水平条形图每个分段中间添加文本,可以通过自定义条形模板实现,这是ngx-charts官方支持的扩展方式,具体步骤如下:

1. 绑定自定义模板属性

在组件模板中,给ngx-charts-normalized-horizontal-bar-chart组件绑定barTemplate属性,指向自定义模板的引用:

<ngx-charts-normalized-horizontal-bar-chart
  [view]="view"
  [scheme]="colorScheme"
  [results]="multi"
  [xAxis]="true"
  [yAxis]="true"
  [legend]="true"
  [showXAxisLabel]="true"
  [showYAxisLabel]="true"
  [xAxisLabel]="'数值'"
  [yAxisLabel]="'类别'"
  [barTemplate]="customBarTemplate"
>
</ngx-charts-normalized-horizontal-bar-chart>

2. 编写自定义模板内容

添加<ng-template>标签,内部保留原条形矩形元素,同时基于条形的位置、宽高信息计算文本居中坐标,添加文本元素:

<ng-template #customBarTemplate let-bar="bar" let-data="data">
  <svg:g>
    <!-- 原条形背景 -->
    <svg:rect
      [attr.x]="bar.x"
      [attr.y]="bar.y"
      [attr.width]="bar.width"
      [attr.height]="bar.height"
      [attr.fill]="bar.color"
    />
    <!-- 居中显示的文本 -->
    <svg:text
      [attr.x]="bar.x + bar.width / 2"
      [attr.y]="bar.y + bar.height / 2"
      text-anchor="middle"
      dominant-baseline="middle"
      style="fill: #fff; font-size: 12px; font-weight: 500;"
    >
      <!-- 可按需修改显示内容,示例为百分比 -->
      {{ (data.value / data.total * 100).toFixed(0) }}%
    </svg:text>
  </svg:g>
</ng-template>

3. 样式与内容适配调整

  • 文本样式:根据条形底色调整fill属性(深色条用白色文本,浅色条用深色文本),修改font-size适配图表尺寸。
  • 显示内容:若无需百分比,直接显示原始数值则替换为{{ data.value }};如需自定义文本,可在数据源中新增displayText字段,模板中使用{{ data.displayText }}。
  • 窄条处理:若条形宽度过窄导致文本溢出,可添加条件判断,比如*ngIf="bar.width > 30"来隐藏窄条上的文本,避免显示错乱。

内容的提问来源于stack exchange,提问作者binga58

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 10:12:17