【问题标题】:Chart.js v3.x time series on x axisx 轴上的 Chart.js v3.x 时间序列
【发布时间】:2021-05-06 22:30:09
【问题描述】:

所以我基本上是在扯头发,因为我无法让它连续工作几个小时。

我正在尝试在 x 轴上以小时为单位的时间和 y 轴上的视图数上做一个(我假设是简单的)折线图。我正在尝试将 x 轴范围设置为 -24 小时到现在。

我的代码如下。我做错了什么?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js"></script>
<div style="width: 500px; height: 500px;"><canvas id="myChart" width="400" height="400"></canvas></div>
    
<script>
    var ctx = document.getElementById('myChart');
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: '# of Votes',
                data: [{x:'1619701200',y:41},{x:'1619704800',y:9},{x:'1619708400',y:21}]
            }]
        },
        options: {
        scales: {
            x: {
                type: 'time',
                min: Date.now() - (24 * 60 * 60 * 1000),
                max: Date.now()
            }
        }
    }
    });

    </script>

编辑:问题是 x 轴没有延伸到 now() 之前的 24 小时。此外,数据集中有 3 个值,但只显示了两个。您甚至可以将 x 值编辑为您想要的任何值,并且整个图表保持不变。

EDIT2:

有人可以帮我解决这个问题吗?我在下面粘贴了我的数据: 我想要达到的目标:

  1. X 轴从现在到 24 小时前,刻度之间的间隔为 1 小时,格式为“d-m-Y H:00:00”。现在的数据是自纪元以来的秒数,如果我需要更改,请告诉我!
  2. Y 轴从 0 到数据集中的最大值
  3. 我必须包含哪些 CDN?我发现关于 chart.js、时刻、适配器等的文档非常不清楚,我在互联网上找到的所有内容都是针对以前版本的。

谢谢!!

<div style="width: 500px; height: 500px;"><canvas id="myChart" width="400" height="400"></canvas></div>
    <script>
        new Chart(document.getElementById("myChart"), {
        type: 'line',
        data: {
            labels: ['1619701200','1619704800','1619708400','1619715600','1619719200','1619722800','1619726400','1619730000','1619733600','1619737200','1619744400','1619773200','1619780400','1619784000','1619787600','1619791200','1619794800','1619798400','1619802000','1619809200','1619812800','1619816400','1619820000','1619823600','1619856000'],
            datasets: [{ 
                data: [41,9,21,80,277,151,68,88,82,48,12,1,97,36,81,21,63,49,44,15,10,44,81,4,9],
                label: "Views",
                borderColor: "#3e95cd",
                fill: false
            },
            { 
                data: [1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,4,1,1],
                label: "Visitors",
                borderColor: "#3e95cd",
                fill: false
            }
            ]
        }
  </script>

【问题讨论】:

标签: chart.js


【解决方案1】:

我们希望你保留你的头发:-)

尝试以下 2 个选项 以获得最新版本的Chart.js

Chart.js v3.2.1(不向后兼容v2.xx

选项 1:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
   // gets you the latest version of Chart.js, now at v3.2.1

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment"></script>
   // You need moment.js and adapter for time or timeseries to work at x-Axis


<div style="width: 500px; height: 500px">
  <canvas id="myChart" width="400" height="400"></canvas>
</div>


<script>
const startDate = new Date(1619701200*1000);
    // first label from your data, times 1000 to get milliseconds,
    // for last 24 hours from now, see further down below

const myLabels = [];
let nextHour = startDate;

let i = 0; // tip: declare i outside for-loop for better performance

for (i; i < 24; i++) {
  nextHour = new Date((1619701200 + (i*3600)) *1000);
  myLabels.push(nextHour);
};

const ctx = document.querySelector('canvas').getContext('2d');

const myChart3x = new Chart(ctx, {
    type: 'line',
    data: {
        labels: myLabels,
        datasets: [{
          data: [41,9,21,80,277,151,68,88,82,48,12,1,97,36,81,21,63,49,44,15,10,44,81,4,9],
          label: "Views",
          borderColor: "#3e95cd",
          fill: false
        },
        {
          data: [1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,4,1,1],
          label: "Visitors",
          borderColor: "#3e95cd",
          fill: false
        }
        ]
    },
    options: {
      scales: {
        x: {
          type: 'timeseries',
          time: {
            unit: 'hour',  // <-- that does the trick here
            displayFormats: {
              hour: 'D-M-Y H:00:00'
            },
            tooltipFormat: 'D-M-Y H:00:00'  // <-- same format for tooltip
          }
        },
        y: {
          min: 0
        }
      }
    }
  });

</script>

这就是您的图表的样子:

如果您想为 x 轴动态计算 从现在开始的最后 24 小时,我建议您改用 moment.js

<script>
   // ...

const startDate = moment().subtract(1, 'd');

const myLabels = [];
let nextHour = startDate;
let i = 0;

for (i; i < 24; i++) {
  nextHour = moment().add(i, 'h');
  myLabels.push(nextHour);
}; 

   // ....
</script>

另外,请注意moment.js 使用的格式字符串略有不同:

'D-M-Y H:00:00' 而不是'd-m-Y H:00:00'

选项 2:

如果您的数据采用 json 格式

data: [{x:1620237600000,y:41},{x:1620241200000,y:9},{x:1620244800000,y:21}]

就像您的第一个代码 sn-p 一样,在 x 轴上使用 minmax:(优点:您不必为 x 轴定义标签数组)

<script>

const ctx = document.querySelector("canvas").getContext("2d");

var myChart = new Chart(ctx, {
  type: "line",
  data: {
    datasets: [{
      label: "Views",
      data: [{x:1620237600000,y:41},{x:1620241200000,y:9},{x:1620244800000,y:21}]
      // x-value without quotes (has to be a number) 
      // and multiply by 1000 to get milliseconds
    },
    {
      label: "Visitors",
      data: [{x:1620237600000,y:1},{x:1620241200000,y:1},{x:1620244800000,y:2}]
    }]
  },
  options: {
    scales: {
      x: {
        type: "time",  // <-- "time" instead of "timeseries"
        min: Date.now() - (24 * 60 * 60 * 1000),
        max: Date.now(),
        time: {
          unit: "hour",  // <-- that does the trick here
          displayFormats: {
            hour: "D-M-Y H:00:00"
          },
          tooltipFormat: "D-M-Y H:00:00"// <-- same format for tooltip
        }
      },
      y: {
        min: 0,
        max: 100
      }
    }
  }
});
</script>

您应该得到以下信息:

我希望我正确理解了您的需求并希望这对您有所帮助。

【讨论】:

  • 你是天赐之物!!非常感谢
  • @B.Smit 感谢您的好评 - 我很高兴它解决了您的问题。您在解释您的问题、添加编辑等方面付出了巨大的努力,因此您应该在回答中付出同样的努力。
【解决方案2】:

它需要更多设置,我已经搜索并通过试验/错误 - 归功于jsfiddle - 这些就是结果。

updated working jsfiddle:

/*
        Source: https://jsfiddle.net/microMerlin/3wfoL7jc/
*/

var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: '# of Votes',
      data: [{
        x: '1619701200',
        y: 41
      }, {
        x: '1619704800',
        y: 9
      }, {
        x: '1619708400',
        y: 21
      }]
    }]
  },
  options: {
    responsive: true,
    scales: {
      xAxes: [{
        min: Date.now() - (24 * 60 * 60 * 1000),
        max: Date.now(),
        type: "linear",
        position: "bottom",
        //stacked: true,
        ticks: {
          //beginAtZero: true,
          userCallback: function(t, i) {
            /*console.log("t: " + t.toString());
            console.log("i: " + i.toString());*/
            return i;
          }
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="width: 500px; height: 500px;"><canvas id="myChart" width="400" height="400"></canvas></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-17
    • 2015-08-13
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多