简体   繁体   English

在Chart.js中格式化条形图的yAxis标签

[英]Format Bar Chart's yAxis labels in Chart.js

I have looked the documentation and similar questions here but I don't seem to find a working solution to my problem. 我在这里查看了文档和类似的问题,但我似乎找不到解决问题的方法。

I'm using Chart.js v.2.1.6, and I have a Bar Chart with percentage values stored as numbers (already multiplied by 100). 我正在使用Chart.js v.2.1.6,并且我有一个条形图,其百分比值存储为数字(已经乘以100)。 I need both y-axis labels and tooltips to display the % sign after the values. 我需要y轴标签和工具提示来显示值后面的%符号。

Someone can shed some light on that matter? 有人可以解释一下这个问题吗?

Here you have my code: 在这里你有我的代码:

var data = {
  "labels": ["Label1", "Label2", "Label3", "Label4", "Label5"],
  "datasets": [{
    "label": "Variation",
    "data": ["56", "-82.3", "25.7", "32.2", "49.99"],
    "borderWidth": 1,
    "backgroundColor": "rgba(231, 76, 60, 0.2)",
    "borderColor": "rgba(231, 76, 60, 1)"
  }]
};

var myBarChart = new Chart($("#myCanvas"), {
  type: 'bar',
  data: data,
  maintainAspectRatio: false
});

And a fiddle: https://jsfiddle.net/tdjk3ncs/ 还有一个小提琴: https//jsfiddle.net/tdjk3ncs/

EDIT: SOLVED 编辑:已解决

I found the solution thanks to miquelarranz, find the updated fiddle: 我找到了解决方案感谢miquelarranz,找到更新的小提琴:

https://jsfiddle.net/tdjk3ncs/7/ https://jsfiddle.net/tdjk3ncs/7/

If you want to add % after the values of the Y-Axis you can do it using scales in your chart configuration. 如果要在Y轴的值之后添加% ,可以使用图表配置中的比例来执行此操作。 Your code will look like this: 您的代码将如下所示:

var myBarChart = new Chart($("#myCanvas"), {
    type: 'bar',
    data: data,
    maintainAspectRatio: false,
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    // Create scientific notation labels
                    callback: function(value, index, values) {
                        return value + ' %';
                    }
                }
            }]
        }
    }
});

Documentation about scales 有关秤的文档

Fiddle updated with the % : Fiddle 小提琴更新了%小提琴

And if you want to modify the text displayed in the tooltips you can easily change it using callback. 如果要修改工具提示中显示的文本,可以使用回调轻松更改它。 You can find more information here Tooltip Callbacks 您可以在此处找到更多信息Tooltip Callbacks

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM