NGX-charts仅显示8个条形,如何展示全部20+数据并适配200x50px区域?
问题
使用ngx-charts组件时,数据包含20条记录,但图表仅显示前8个条形,剩余记录未展示。同时需要让图表适配200x50px的小区域。
数据
single: any[] = [ { "name": "2020/05/27", "value": 8 }, { "name": "2020/06/24", "value": 5 }, { "name": "2020/07/04", "value": 4 }, { "name": "2020/08/02", "value": 3 }, { "name": "2020/09/07", "value": 9 }, { "name": "2020/09/22", "value": 1 }, { "name": "2020/09/23", "value": 5 }, { "name": "2020/10/05", "value": 6 }, { "name": "2020/07/04", "value": 9 }, { "name": "2020/07/04", "value": 9 }, { "name": "2020/07/04", "value": 9 }, { "name": "2020/07/04", "value": 9 }, { "name": "2020/07/04", "value": 9 }, { "name": "2020/07/04", "value": 9 }, { "name": "2020/07/04", "value": 9 }, { "name": "2020/07/04", "value": 9 }, { "name": "2020/07/04", "value": 9 }, { "name": "2020/07/04", "value": 9 }, { "name": "2020/07/04", "value": 9 }, { "name": "2020/07/04", "value": 9 } ];
当前输出效果

使用的代码
配置项
chartConfig: any = { width: 1210, // 210 height: 500, // 30 showXAxis: false, // Default Value: true showYAxis: false, // Default Value: true gradient: false, // Default Value: false showLegend: false, // Default Value: true showXAxisLabel: false, // Default Value: true showYAxisLabel: false, // Default Value: true tooltipDisabled: true, // Default Value: true xAxisLabel: 'Country', // Default Value: 'Country' yAxisLabel: 'Population' // Default Value: 'Population' };
模板代码
<app-user-chart [data]="single" [chartConfig]="chartConfig"></app-user-chart>
解决方案
要展示全部20条记录并适配200x50px的小区域,可按以下步骤调整:
1. 匹配目标尺寸并禁用数据截断
- 先将图表配置的宽高改为200x50,贴合目标区域:
chartConfig: any = { width: 200, height: 50, showXAxis: false, showYAxis: false, showLegend: false, showXAxisLabel: false, showYAxisLabel: false, tooltipDisabled: true // 移除其他无关配置项 }; - 针对内部的ngx-charts条形组件(如
ngx-charts-bar-vertical),添加[limit]="20"属性,强制渲染全部20条数据,避免自动截断:<!-- 假设app-user-chart内部封装了该组件,需确保limit属性传递生效 --> <ngx-charts-bar-vertical [data]="data" [limit]="20" [width]="chartConfig.width" [height]="chartConfig.height" [showXAxis]="chartConfig.showXAxis" [showYAxis]="chartConfig.showYAxis" [showLegend]="chartConfig.showLegend" [showXAxisLabel]="chartConfig.showXAxisLabel" [showYAxisLabel]="chartConfig.showYAxisLabel" [tooltipDisabled]="chartConfig.tooltipDisabled" ></ngx-charts-bar-vertical>
2. 压缩条形间距
- 设置
barPadding属性减少条形之间的空白,让20条条形能紧凑排列:
可根据实际显示效果调整<ngx-charts-bar-vertical [barPadding]="0.1" <!-- 其他属性 --> ></ngx-charts-bar-vertical>barPadding的数值(范围0-1),数值越小间距越窄。
3. 修复重复数据问题(可选)
- 数据中存在大量
name为2020/07/04的重复记录,ngx-charts会自动合并同名称的数据。如果需要每条记录单独展示,需为重复的name添加唯一标识:this.single = this.single.map((item, index) => { if (item.name === '2020/07/04') { return { ...item, name: `${item.name}_${index}` }; } return item; });
内容的提问来源于stack exchange,提问作者Vivek Kumar Shukla
相关产品推荐
相关产品推荐

