Chartjs线图只有一点 - 如何居中

时间:2015-12-11 14:23:31

标签: chart.js

我有一张chartjs折线图,用于显示不同产品在一系列日期的销售情况。用户可以选择日期范围(例如从2015-12-01到2015-12-10)来查看每天的销售情况,这很好并且可以正常工作。

但如果用户只选择一天(范围从2015-12-01到2015-12-01),他会得到正确的图表,但看起来不太好:

enter image description here

如您所见,这些点都贴在y轴上。是否有可能将图中的点居中?

这应该是什么样子:

enter image description here

4 个答案:

答案 0 :(得分:10)

您可以检查标签(或数据)数组的长度,并使用空字符串标签和空值向左和向右添加虚拟不可渲染点,如此

var chartData = {
  labels: ['', "A", ''],
  datasets: [
    {
      fillColor: "rgba(255, 52, 21, 0.2)",
      pointColor: "#da3e2f",
      strokeColor: "#da3e2f",
      data: [null, 20, null]
    },
    {
      fillColor: "rgba(52, 21, 255, 0.2)",
      strokeColor: "#1C57A8",
      pointColor: "#1C57A8",
      data: [null, 30, null]
    },
  ]
}

小提琴 - https://jsfiddle.net/pf24vg16/

答案 1 :(得分:0)

想要添加上面的答案并说我对时间序列散点图有类似的效果:

if (values.length === 1) {
        const arrCopy = Object.assign({}, values);
        values.unshift({x: arrCopy[0].x - 86400000, y: null});
        values.push({x: arrCopy[0].x + 2 * 86400000, y: null});
}

然而,只处理单个点。要为多个点添加功能,我执行了以下操作:

const whether = (array) => {
    const len = array.length;
    let isSame = false;
    for (let i = 1; i < len; i++) {
        if (array[0].x - array[i].x >= 43200000) {
            isSame = false;
            break;
        } else {
            isSame = true;
        }
    }
    return isSame;
}
if (values.length === 1 || whether(arr[0])) {
        const arrCopy = Object.assign({}, values);
        values.unshift({x: arrCopy[0].x - 86400000, y: null});
        values.push({x: arrCopy[0].x + 2 * 86400000, y: null});
}

您可能会注意到我只是在x值中减去/添加一天(以毫秒为单位)。说实话,我只是在最糟糕的时候和moment.js一起放弃哈哈。希望这有助于其他人!

注意:我的代码的时间容差为43200000或12小时。你可以使用moment.js来比较天数,如果你运气好的话比我今晚做的好:)

答案 2 :(得分:0)

对于您的特定问题,请尝试如下修改options-> scales-> xAxes选项:

options: {
      title: {
         display: true,
         text: 'mytitle1'
      },
      scales: {
         xAxes: [{
            type: 'linear',
            ticks: {
               suggestedMin: 0,
               suggestedMax: (11.12*2),
               stepSize: 1 //interval between ticks
            }
         }],

更多信息,请访问:Chart JS: Ignoring x values and putting point data on first available labels

答案 3 :(得分:0)

不是使用空白参数对标签和值进行硬编码,而是在选项下的scale内部使用offset属性。  秤:{        x轴:[{          offset:true, }} }