如何在chartjs中将起始值设置为"0"?

Sug*_*Raj 88 charts chart.js

这是我的代码.我需要在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);
   }     
Run Code Online (Sandbox Code Playgroud)

xna*_*kos 227

对于Chart.js 2.*,比例从零开始的选项列在线性比例配置选项下.这用于数值数据,最有可能是y轴的情况.所以,你需要使用这个:

options: {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    }
}
Run Code Online (Sandbox Code Playgroud)

此处还提供一个示例折线图,其中该选项用于y轴.如果您的数值数据在x轴上,请使用xAxes而不是yAxes.请注意,数组(和复数)用于yAxes(或xAxes),因为您可能还有多个轴.


Wou*_*bie 75

现在(5 年后的 3.x 版本)有点不同

options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

请参阅: https: //www.chartjs.org/docs/latest/#creating-a-chart

  • 感谢您提供 Chart.js 3 解决方案。 (2认同)

tul*_*tto 8

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

defaults: {
  global: {...},
  scale: {
    ...
    ticks: { min: 0 },
  }
},
Run Code Online (Sandbox Code Playgroud)

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


wma*_*ash 5

请添加此选项:

//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
Run Code Online (Sandbox Code Playgroud)

(参考:Chart.js

注意:我发布的原始解决方案是针对 Highcharts 的,如果您不使用 Highcharts,请删除标签以避免混淆

  • 它不工作。我正在使用最新版本的chartjs v2.1 (4认同)