Javascript 如何在chart.js图形中使x轴从0开始?

Javascript 如何在chart.js图形中使x轴从0开始?,javascript,jquery,html,css,chart.js,Javascript,Jquery,Html,Css,Chart.js,我正在使用chart.js库,我遇到了一个问题。我希望年轴从0开始。现在它是从负值开始的(在我的例子中是-50) 目前它是这样来的- 我想要的- 我正在尝试的- var配置={ 类型:'bar', 数据:{ 标签:[“0年”、“1年”、“2年”、“3年”、“4年”、“5年”、“6年”], 数据集:[{ 键入:“行”, 标签:“累计流量”, 数据:[0,-50,20,30,40,50], 边框颜色:“红色”, 填充:假, 线张力:0, borderJoinStyle:'斜接', xAxes:[

我正在使用chart.js库,我遇到了一个问题。我希望年轴从0开始。现在它是从负值开始的(在我的例子中是-50)

目前它是这样来的-

我想要的-

我正在尝试的-
var配置={
类型:'bar',
数据:{
标签:[“0年”、“1年”、“2年”、“3年”、“4年”、“5年”、“6年”],
数据集:[{
键入:“行”,
标签:“累计流量”,
数据:[0,-50,20,30,40,50],
边框颜色:“红色”,
填充:假,
线张力:0,
borderJoinStyle:'斜接',
xAxes:[{
百分比:0.4
}]
}, {
类型:'bar',
标签:“Benifit(一次性)”,
背景色:“005998”,
数据:[40,50,60,80,50,60],
}, ]
},
选项:{
标题:{
显示:对,
文本:“自定义图表标题”
},
比例:{
xAxes:[{
时间:{
显示格式:{
季度:'yyy'
}
},
贝吉纳泽罗:是的,
百分比:0.3,
id:'x轴标签',
位置:'底部',
scaleStartValue:20,
网格线:{
显示:假
},
}],
雅克斯:[{
id:'y轴标签',
滴答声:{
最高:300,
最低:-50,
步长:50,
},
位置:'左',
网格线:{
显示:假
},
}]
},
图例:{
位置:'右'
},
MaintaintAspectRatio:false,
scaleBeginAtZero:真
}
};
var ctx=document.getElementById(“myChart”).getContext(“2d”);
新图表(ctx,配置)
.GraphContain{
最大高度:500px;
位置:相对位置;
}

在阅读了core scale源代码后,我想出了一种方法来配置图表,使其非常接近您想要的行为

它要求我们手动设置网格线颜色,并操作内部缩放实例
ticks
数组(scale draw方法使用该数组在画布上绘制)

首先,为了隐藏一些网格线但显示其他网格线,我使用了
gridlines.color
属性,并传入了一个颜色数组,其中第一个索引颜色是默认的网格线颜色,所有其他颜色都是白色的(第一个索引用于为“零”网格线着色)。注意,由于我们稍后将操作内部刻度
刻度
数组,因此必须使用白色向颜色数组添加额外的索引。这是我的意思的一个例子

gridLines: {
    // since we only want to show the "zero line" gridline (chart.js
    // uses the color of the first index to paint this line), we
    // set the first index to the default color and all others to white
    // note, later we add a "dummy" tick (explained later) so the length
    // of this array has to be 1 greater than the number of gridlines you
    // want displayed
    color: [
      "rgba(0, 0, 0, 0.1)", // this is for the zero line
      "rgb(255, 255, 255)",
      "rgb(255, 255, 255)",
      "rgb(255, 255, 255)",
      "rgb(255, 255, 255)",
      "rgb(255, 255, 255)",
      "rgb(255, 255, 255)",
      "rgb(255, 255, 255)",
      "rgb(255, 255, 255)",],
  }
}
接下来,我们使用来操纵内部刻度
刻度
数组,以强制网格线按您的需要显示。下面是适用于您的用例的实现

// we will use this callback to manipulate the ticks array
// before they are drawn on the canvas
afterTickToLabelConversion: function(scaleInstance) {
  // the top gridline (which is at index 0) is always shown 
  // so to overcome this we add a "dummy" tick at index 0
  scaleInstance.ticks.unshift(null);

  // we have to do the same this to this tick array as well
  // because it uses the values in this array to map to the data
  scaleInstance.ticksAsNumbers.unshift(null);

  // since we have added an extra tick, we need to move the 
  // zero line index to point to the new index of 0
  scaleInstance.zeroLineIndex++
}
所以,把所有这些放在一起,你会得到一张像这样的图表


查看此示例(注意,我留下了其他解决此问题的尝试…请参见底部的选项3)。

您想要的图形并不理想,因为折线图与标签重叠。尝试重叠将不会是一个问题。我只希望x轴从0开始@DroidNoobI认为我有一个比下面的答案更简单的解决方案,但不知道这个问题是否已经死了。@Jordanwillist这个问题仍然存在;)让我明天尝试第三种选择,我有一个想法。我猜想​ 你已经看到我的答案了?