angularjs - Angular JS 中的条形图使用 Chartjs
问题描述
我正在我的 AngularJS 应用程序中使用 Chartjs 制作条形图。我能够渲染图表,但是,我无法找到一种方法来显示每个条形图的值。我找到的解决方案是针对 Angular 应用程序而不是针对 AngularJs 应用程序的。
这是我的画布标签:
我的 JS 文件代码:
$scope.labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July'];
$scope.data = [[75, 63, 59, 79, 13, 91, 113]];
$scope.ColorBar = ['#90EE90', '#FF6600'];
$scope.DataSetOverride = [{ yAxisID: 'y-axis-1' }];
$scope.options = {
legend: { display: true },
responsive: true,
scales: {
yAxes: [
{
id: 'y-axis-1',
type: 'linear',
display: true,
position: 'left'
}]
}
}
解决方案
如果您不想使用 datalabels 插件,您可以编写自己的基本版本作为内联插件,如下所示:
const customDatalabalesPlugin = {
id: 'customDatalabels',
afterDatasetsDraw: (chart, args, opts) => {
const {
ctx,
_metasets
} = chart;
const lineHeight = ctx.measureText('M').width;
const color = opts.color || 'black';
for (let i = 0; i < chart.data.datasets.length; i++) {
const meta = chart.getDatasetMeta(i)
meta.data.forEach((el) => {
//console.log(el)
const dpVal = el._chart.data.datasets[el._datasetIndex].data[el._index];
const text = dpVal.toString();
const textWidth = ctx.measureText(text).width;
ctx.fillStyle = color;
ctx.fillText(text, (el._model.x - textWidth / 2), (el._model.y - lineHeight));
});
}
}
}
const options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12.4, 19.234, 3.23213, 5.4, 2, 3],
borderColor: 'pink'
}]
},
options: {
plugins: {
customDatalabels: {
color: 'green', // Color each character individual collor
// color: 'pink' // Color whole label this collor
}
}
},
plugins: [customDatalabalesPlugin]
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>
关于在插件中使用私有变量,可以节省地完成,因为chart.js 不会再发布版本2,因此它们不会再被更改。
推荐阅读
- python - 挑战:关于一个元素(不包括自身)的嵌套循环的最 Pythonic 方式
- vba - 如何在主窗体的子窗体中禁用按钮
- gnu-make - 如何设置“make install”来检查已安装库/bins 的 md5 并且仅在更改时安装?
- python - 保存到镶木地板文件时如何使用新的 Int64 熊猫对象
- vue.js - 如何将 mdbootstrap 应用于我的 vue 项目?
- python-3.x - 使用 AWS CLI 将包含子文件夹和文件的文件夹从服务器复制到 S3
- intellij-idea - 在intellij中更改导入项目的默认路径
- c++ - 将整个 QAbstractTableModel 传递给 QML
- typescript - 使用 typeof 作为参数类型
- javascript - 将字符串转换为数组中的键值对