【问题标题】:Data Labels on top of points in line charts折线图中点顶部的数据标签
【发布时间】:2018-03-28 04:57:58
【问题描述】:

我正在使用 Angular2 和 ng2-charts 来创建折线图。但我试图将数据标签放在最重要的位置,就像链接中图像上的条形图中的数据标签一样: bar chart

我找到了chart.js plugin for data labels,但我不知道如何将它与 ng2-charts 一起使用。

您可以在链接中看到我如何制作图表的简单示例:http://plnkr.co/edit/GcuZd5A4J6TL29vAyTua?p=preview

谁能帮帮我?!

【问题讨论】:

    标签: angular chart.js ng2-charts


    【解决方案1】:

    您可以构建一个插件来使其正常工作。我目前在一个 vue 版本中工作,但我已经尽力为你调整它。

    模板

    template: `
      <base-chart
        class="chart"
        [datasets]="datasets"
        [labels]="labels"
        [options]="options"
        [chartType]="'line'"
        [plugin]="dataLabelPlugin">
      </base-chart>
    `
    

    js添加插件

    private options = {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true
          }
        }]
      }
      plugins: [{
        afterDatasetsDraw: this.dataLabelPlugin
      }]
    };
    

    Js 定义了一个插件,在每个动画之后绘制数字。您可能需要根据上下文传入您正在修改的图表。

    private dataLabelPlugin = function(chart, easing) {
        // To only draw at the end of animation, check for easing === 1
        const ctx = chart.ctx;
        const fontSize = 12;
        const fontStyle = 'normal';
        const fontFamily = 'open sans';
        const padding = 5;
    
        chart.data.datasets.forEach((dataset, key) => {
            let meta = chart.getDatasetMeta(key);
            if (!meta.hidden) {
                meta.data.forEach((element, index) => {
                    let position = element.tooltipPosition();
                    // Just naively convert to string for now
                    let dataString = dataset.data[index].toString();
    
                    ctx.fillStyle = '#676a6c';
    
                    ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);
                    // Make sure alignment settings are correct
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';
                    ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
                });
            }
        });
    };
    

    如果你得到这个工作,让我知道,我可以做出改变,使这个答案更正确。

    【讨论】:

      猜你喜欢
      • 2016-11-18
      • 2017-05-03
      • 1970-01-01
      • 2020-11-07
      • 1970-01-01
      • 1970-01-01
      • 2017-11-30
      • 2023-01-31
      • 1970-01-01
      相关资源
      最近更新 更多