如何在Chart.js中将起始值设置为“0”?

168

这是我的代码。我需要在x和y轴的比例尺中都将初始值设置为“0”。我已经尝试了最新版本的比例尺选项。

graphOptions = {               
            ///Boolean - Whether grid lines are shown across the chart
            scaleShowGridLines: false,    
            tooltipTitleTemplate: "<%= label%>",
            //String - Colour of the grid lines
            scaleGridLineColor: "rgba(0,0,0,.05)",
            //Number - Width of the grid lines
            scaleGridLineWidth: 1,
            //Boolean - Whether to show horizontal lines (except X axis)
            scaleShowHorizontalLines: true,
            //Boolean - Whether to show vertical lines (except Y axis)
            scaleShowVerticalLines: true,
            //Boolean - Whether the line is curved between points
            bezierCurve: true,
            //Number - Tension of the bezier curve between points
            bezierCurveTension: 0.4,
            //Boolean - Whether to show a dot for each point
            pointDot: true,
            //Number - Radius of each point dot in pixels
            pointDotRadius: 4,
            //Number - Pixel width of point dot stroke
            pointDotStrokeWidth: 1,               
            pointHitDetectionRadius: 20,               
            datasetStroke: true,
            datasetStrokeWidth: 2,
            datasetFill: true,               
            legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
        };
        var LineChart = new Chart(ctx).Line(graphData, graphOptions);
   }     

我发现在数据列表中添加一个额外的零而不指定名称就能解决问题。 - 5idneyD
4个回答

418

对于Chart.js 2.*,使刻度从零开始的选项在线性刻度的配置选项中列出。这适用于数字数据,这很可能是您y轴的情况。所以,您需要使用以下内容:

options: {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    }
}

这里还提供了一个示例折线图(链接),其中选项用于y轴。如果您的数值数据在x轴上,请使用xAxes而不是yAxes。请注意,使用数组(复数形式)来表示yAxes(或xAxes),因为您可能需要多个坐标轴。


@SuganthanRaj 没问题!只要确保您查阅Chart.js 2.0的文档。与1.0版本相比,有很多变化,大多数在线示例适用于1.0版本。;) - xnakos
例如,scaleShowVerticalLines 在2.0中无效。或者是工具提示模板。总的来说,选项在2.0中采用分层方法。 - xnakos
这个回答已经过时了,下面Wouter Debie的回答对我有用。 - Bruno Aquino

71

2
感谢提供 Chart.js 3 的解决方案。 - HartleySan

11

如果您需要将其用作默认配置,只需将min:0放置在节点defaults.scale.ticks内,如下所示:

defaults: {
  global: {...},
  scale: {
    ...
    ticks: { min: 0 },
  }
},

参考资料:https://www.chartjs.org/docs/latest/axes/


5
请添加这个选项:
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,

(参考: Chart.js)

注意: 我最初发布的解决方案是针对Highcharts的,如果您没有使用Highcharts,请删除该标签以避免混淆。


4
无效。我正在使用最新版本的Chart.js v2.1。 - Suganthan Raj
@wmash,我需要从预定义的值开始绘制图表。你知道该怎么做吗?我尝试将这个选项设置为true和false,但它不起作用。 - Michael.D
1
这是不正确的,应该删除。你需要的是 beginAtZero: true - triple

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接