图表JS:如何设置单位?

Rom*_*man 7 jquery chart.js

如何在悬停在条形图上时将单位添加到标签中?我查看了文档,但找不到答案.

http://www.chartjs.org/docs/#bar-chart 图表单位

我想添加例如(mm,°C,)我的代码:

            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]

            }
Run Code Online (Sandbox Code Playgroud)

Dam*_*ien 9

我发现 Chart.js 的更高版本(截至撰写时为 v3.7.0)中的选项 API 已更改。

\n

添加温度单位的示例如下:

\n
const options = {\n    plugins: {\n        tooltip: {\n            callbacks: {\n                label: (item) =>\n                    `${item.dataset.label}: ${item.formattedValue} \xc2\xb0C`,\n            },\n        },\n    },\n}\n
Run Code Online (Sandbox Code Playgroud)\n


mmo*_*mad 7

您可以使用工具提示回调配置向工具提示添加单位.

例如,以下是如何在工具提示中添加"GB"单位:

const options = {
  tooltips: {
    callbacks: {
      label: (item) => `${item.yLabel} GB`,
    },
  },
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你!请注意[IE11 不支持模板文字](https://caniuse.com/#feat=template-literals)。像`item.yLabel + " GB"` 之类的东西会更通用。 (3认同)