如何在Chart.JS条形图中的最后一个条形图上方添加标签? [英] How can I add a label above just the last bar in a Chart.JS bar chart?

查看:115
本文介绍了如何在Chart.JS条形图中的最后一个条形图上方添加标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个如此的条形图:

  var ctxForecastChart = $(#forecastLineChart)。get(0 ).getContext( 2D); 
var forecastChartData = {
labels:[
Total Sales
],
数据集:[
{
label:8 / 28/2016 - 2016年9月3日,
backgroundColor:rgba(255,0,0,0.75),
hoverBackgroundColor:rgba(255,0,0,1),
数据:[240]
},
{
label:2016/9/25 - 2016年2月10日,
backgroundColor:rgba(255,153, 0,0.75),
hoverBackgroundColor:rgba(255,153,0,1),
数据:[272]
},
{
label: 2016年9月18日 - 2016年9月24日,
backgroundColor:rgba(255,255,0,0.75),
hoverBackgroundColor:rgba(255,255,0,1),
数据:[250]
},
{
label:2016年9月4日 - 2016年9月9日,
backgroundColor:rgba(0,255,0, 0.75),
hoverBackgroundColor:rgba(0,255,0,1),
数据:[232]
},
{
标签:9 / 11/2016 - 2016/9/17,
backgroundColor:r gba(0,0,255,0.75),
hoverBackgroundColor:rgba(0,0,255,1),
data:[244]
}]
};

var forecastOptions = {
工具提示:{
已启用:true
}
};

var forecastBarChart = new Chart(ctxForecastChart,
{
type:'bar',
data:forecastChartData,
options:forecastOptions
});

看起来像这样:



< a href =https://i.stack.imgur.com/dQRgr.png =nofollow noreferrer>



我想要做的是在最后一个条形图(蓝色条形图)上方添加一个标签,其间的百分比差异前一个/第四个和那个。在这种情况下,该值应为+ 5.2%,使其如下所示:





我认为这将需要一个afterDraw()事件的registring,但它应该看起来的细节是超出我的。



UPDATE



如果我将此添加到建议的代码中:

  if(chartInstance.id!== 2)返回; //只影响这一个

在上下文中:

  afterDraw:function(chartInstance){
if(chartInstance.id!== 2)return; //只影响这个
//我们得到画布上下文
var ctx = chartInstance.chart.ctx;

...结果比没有它好一点(这会破坏我的第一个(馅饼)图表并完全抹杀了接下来的两个(包括这里讨论的那个):





正如你所看到的那样,饼图仍然被剔除,两个条形图中的数值都缩小了,好像一个吃人的部落已经对它们进行了一系列的诡计。而且,没有任何附加价值最后一栏。

解决方案

首先,你正好考虑使用 afterDraw


I am creating a bar chart like so:

var ctxForecastChart = $("#forecastLineChart").get(0).getContext("2d");
var forecastChartData = {
    labels: [
        "Total Sales"
    ],
    datasets: [
    {
        label: "8/28/2016 - 9/3/2016",
        backgroundColor: "rgba(255,0,0,0.75)",
        hoverBackgroundColor: "rgba(255,0,0,1)",
        data: [240]
    },
    {
        label: "9/25/2016 - 10/2/2016",
        backgroundColor: "rgba(255,153,0,0.75)",
        hoverBackgroundColor: "rgba(255,153,0,1)",
        data: [272]
    },
    {
        label: "9/18/2016 - 9/24/2016",
        backgroundColor: "rgba(255,255,0,0.75)",
        hoverBackgroundColor: "rgba(255,255,0,1)",
        data: [250]
    },
    {
        label: "9/4/2016 - 9/10/2016",
        backgroundColor: "rgba(0,255,0,0.75)",
        hoverBackgroundColor: "rgba(0,255,0,1)",
        data: [232]
    },
    {
        label: "9/11/2016 - 9/17/2016",
        backgroundColor: "rgba(0,0,255,0.75)",
        hoverBackgroundColor: "rgba(0,0,255,1)",
        data: [244]
    }]
};

var forecastOptions = {
    tooltips: {
        enabled: true
    }
};

var forecastBarChart = new Chart(ctxForecastChart,
{
    type: 'bar',
    data: forecastChartData,
    options: forecastOptions
});

This looks like so:

What I want to do is to add a label above the last bar (the blue one) with a percentage difference between the previous/4th one and that one. In this case, the value should be "+5.2%" so that it looks like this:

I reckon this will require the registring of an afterDraw() event, but the nitty-gritty of how it should look is beyond me.

UPDATE

If I add this to the proposed code:

if (chartInstance.id !== 2) return; // affect this one only

In context:

afterDraw: function (chartInstance) {
    if (chartInstance.id !== 2) return; // affect this one only
    // We get the canvas context
    var ctx = chartInstance.chart.ctx;

...the results are a little better than without it (which mangles my first (pie) chart and completely obliterates the next two (including the one being discussed here):

As you can see, the pie chart is still hosed, and the values in the two bar charts are shrunken down as if a cannibalistic tribe has perpetrated its inicuous tricks on them. And, there is no value added atop the final bar.

解决方案

First, you were right thinking about using the afterDraw event with a plugin and I understand it can be quite a mess to find what we really want in all the data and options.

Yet, follows a plugin that will help you do what you are looking for :

var myPlugin = {
    afterDraw: function(chartInstance) {
        // We get the canvas context
        var ctx = chartInstance.chart.ctx;

        // And set all the properties we need
        ctx.font = Chart.helpers.fontString(14, 'bold', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';
        ctx.fillStyle = '#666';

        // We get the number of datasets we have in your chart
        var numOfDatasets = chartInstance.config.data.datasets.length;

        // For every dataset in our chart ...
        chartInstance.data.datasets.forEach(function(dataset) {

            // If it is not the last dataset, we return now (no action at all)
            if (dataset._meta[0].controller.index != numOfDatasets - 1) return;

            // For every data in the dataset ...
            for (var i = 0; i < dataset.data.length; i++) {

                // We get the previous dataset (to compare later)
                var previousDataset = chartInstance.config.data.datasets[dataset._meta[0].controller.index - 1];
                // And get the model of the current value
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;

                // We calculate the percentage difference with the previous
                var value = ((dataset.data[i] - previousDataset.data[i]) / previousDataset.data[i]) * 100;

                // And write it with a "%" symbol
                // The ternary adds a "+" symbol if it is a positive value
                ctx.fillText((value > 0 ? "+" : "") + value.toFixed(1) + "%", model.x, model.y);
            }
        });
    }
};

Chart.pluginService.register(myPlugin);


You can see this code working on this jsFiddle and here is its result :

这篇关于如何在Chart.JS条形图中的最后一个条形图上方添加标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆