14

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]

            }
Roman
  • 1,118
  • 3
  • 15
  • 37

3 Answers3

19

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`,
    },
  },
}
Pang
  • 9,564
  • 146
  • 81
  • 122
mmohammad
  • 2,334
  • 2
  • 14
  • 23
  • 3
    Thanks for this! Note that [template literals are not supported in IE11](https://caniuse.com/#feat=template-literals). Something like `item.yLabel + " GB"` will work more universally. – rinogo Feb 21 '18 at 21:05
8

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`,
            },
        },
    },
}
Damien
  • 513
  • 5
  • 10
3

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';
        }
    },
    }