Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Charts JS: How to set units?

How can I add units to a labels when hovered over bars? I looked in the documentation but can't find the answer.

http://www.chartjs.org/docs/#bar-chart charts units

I want to add for example (mm, °C,) my code:

            options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:false                            
                    },
                    scaleLabel: {
                        display: true,
                        labelString: 'Temperature'

                    }
                }]                    
            },

            title: {
                display: true,
                text: 'Temperature'
            },

            tooltips:{
                enabled: true,
                mode: 'label'                    

            }
        }
    });

datasets: [
            {
                label: "Temperature",
                type: "line",
                backgroundColor: "transparent",                    
                borderColor: "#C72448",
                pointBackgroundColor: "#C72448",
                pointBorderColor: "#fff",
                pointHoverBackgroundColor: "#fff",
                pointHoverBorderColor: "rgba(179,181,198,1)",
                data: [19,20,21,24,27,29,30,31,30,28,25,21]

            }
like image 793
Roman Avatar asked Sep 15 '16 12:09

Roman


3 Answers

I found that the options API has changed in later versions of Chart.js (v3.7.0 as of writing).

An example of adding temperature units is as follows:

const options = {
    plugins: {
        tooltip: {
            callbacks: {
                label: (item) =>
                    `${item.dataset.label}: ${item.formattedValue} °C`,
            },
        },
    },
}
like image 152
Damien Avatar answered Oct 19 '22 20:10

Damien


You can add units to tooltips using tooltip callbacks configuration.

For example, here is how to add "GB" unit to the tooltip:

const options = {
  tooltips: {
    callbacks: {
      label: (item) => `${item.yLabel} GB`,
    },
  },
}
like image 19
mmohammad Avatar answered Oct 19 '22 20:10

mmohammad


for Angular 7, This works for me, might help you:

options: {
    tooltips: {
      callbacks: {
        label: (tooltipItems, data) => {
            return data.datasets[tooltipItems.datasetIndex].data[tooltipItems.index] + ' GB';
        }
    },
    }
like image 3
mayank arora Avatar answered Oct 19 '22 21:10

mayank arora