json - 如何以角度从图表(条形图/饼图等)上的 Json 文件中获取数据?
问题描述
现在我正在做的是直接从 ts 文件中获取数据,如下所示,使用 ng-2 图表和 chart.js:`
import { Component } from '@angular/core';
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Label } from 'ng2-charts';
@Component({
selector: 'app-bar-chart',
templateUrl: './bar-chart.component.html',
styleUrls: ['./bar-chart.component.css']
})
export class BarChartComponent {
barChartOptions: ChartOptions = {
responsive: true,
};
barChartLabels: Label[] = ['Apple', 'Banana', 'Kiwifruit', 'Blueberry', 'Orange', 'Grapes'];
barChartType: ChartType = 'bar';
barChartLegend = true;
barChartPlugins = [];
barChartData: ChartDataSets[] = [
{ data: [45, 37, 60, 70, 46, 33], label: 'Best Fruits' }
];
}
`
HTML 文件:`
<div class="chart-wrapper">
<canvas baseChart
[datasets]="barChartData"
[labels]="barChartLabels"
[options]="barChartOptions"
[plugins]="barChartPlugins"
[legend]="barChartLegend"
[chartType]="barChartType">
</canvas>
</div>
`
来源是使用 ng-2charts 和 charts.js 的 Angular Charts
所以,我现在想要显示相同的图表,但使用 json 文件意味着来自 json 虚拟数据,请帮助我实现这一点
json文件:
[
{
"name": "Java",
"data": [12, 10, 19]
},
{
"name": "Python",
"data": [23, 18, 20]
}
]
解决方案
您可以转换数据:
let data = [ { "name": "Java", "data": [12, 10, 19] }, { "name": "Python", "data": [23, 18, 20] } ]
let colors = ["red","blue","green"]; // must match the array size, or include the color inside data
let chartData = data.map((x,i)=> {
return {
label: x.name,
backgroundColor: colors[i],
data: x.data
}
})
console.log(chartData)
用于读取外部 JSON 文件:
import {readFileSync} from 'fs';
// create a function in service or the component
readJsonFile(path:string){
return JSON.parse(readFileSync(path, 'utf8'));
}
然后您可以使用该函数获取json并将其传递给chartJS
推荐阅读
- javascript - 使用深色或浅色模式
- python-3.x - 如何从外部访问函数内部声明的列表而不在python中调用函数?
- windows - 如何添加 Pre-Commit SVN Hook 来限制 Windows Server 大小超过 10 MB 的文件?
- javascript - 如何获取动态添加输入的值
- azure - 使用逻辑应用读取 azure blob 存储文件夹中的文件列表,并将带有扩展名的文件名插入 Azure SQL
- python - Tkinter 回调和 googletrans api 中的异常
- cuda - cuda-memcheck 无效的 __global__ 读取大小为 4
- python - 为什么我得到 discord.py AttributeError: 'str' object has no attribute 'trigger_typing'
- java - 集群中其他节点未释放石英锁导致微服务启动失败
- amazon-web-services - aws sdk boto3 使用 describe_security_groups()