admin管理员组

文章数量:1355532

Concerning this jsfiddle which uses chartjs v3.9.1 and the date-fns adapter:

/

  1. I'm trying to format the tick labels in the function tick_label but I'm only getting a string as input. Is there a way to get the full Date object so I can include the month and day-of-month in the tick label if I want?

  2. Is there a way to specify which times to use for tick lines along the time axis?

Here is the code from the fiddle:

var chart1

function tick_label(xvalue) {
    console.log("xvalue:", xvalue, "type:", typeof(xvalue))
    return xvalue
}

function doit() {
  let t0 = 1742662800*1000; // Sat Mar 22 12:00:00 CDT 2025
  let N = 31
  data = [...Array(N)].map((a,i) =>
               ({ 'x': new Date(i*3600000+t0),
                 'y': ~~(Math.random()*40)
               }))  
  config = {
    type: "scatter",
    data: { datasets: [{ label: "Random Values", data: data }] },
    options: {
      scales: {
        x: { type: 'time', ticks: { callback: tick_label, color: 'red' } }
      }
    }
  }
  chart1 = new Chart(document.getElementById('chart1'), config);
}
doit()

Concerning this jsfiddle which uses chartjs v3.9.1 and the date-fns adapter:

https://jsfiddle/0a6c1ty5/22/

  1. I'm trying to format the tick labels in the function tick_label but I'm only getting a string as input. Is there a way to get the full Date object so I can include the month and day-of-month in the tick label if I want?

  2. Is there a way to specify which times to use for tick lines along the time axis?

Here is the code from the fiddle:

var chart1

function tick_label(xvalue) {
    console.log("xvalue:", xvalue, "type:", typeof(xvalue))
    return xvalue
}

function doit() {
  let t0 = 1742662800*1000; // Sat Mar 22 12:00:00 CDT 2025
  let N = 31
  data = [...Array(N)].map((a,i) =>
               ({ 'x': new Date(i*3600000+t0),
                 'y': ~~(Math.random()*40)
               }))  
  config = {
    type: "scatter",
    data: { datasets: [{ label: "Random Values", data: data }] },
    options: {
      scales: {
        x: { type: 'time', ticks: { callback: tick_label, color: 'red' } }
      }
    }
  }
  chart1 = new Chart(document.getElementById('chart1'), config);
}
doit()
Share Improve this question asked Mar 29 at 19:32 ErikRErikR 52.1k9 gold badges77 silver badges136 bronze badges 1
  • 1 For question 2, see stackoverflow/questions/61984352/… – James Commented Mar 29 at 20:42
Add a comment  | 

1 Answer 1

Reset to default 1

The tick_label function is additionally passed the index and the ticks array (docs). You can get the numeric value from there.

function tick_label(xvalue, i, ticks) {
    let numeric = ticks[i].value;
    let date = new Date(numeric);
    console.log("xvalue:", xvalue, "type:", typeof(xvalue), "numeric:", numeric, "date:", date);
    return xvalue;
}

本文标签: javascriptControlling tick marks and lines in chartjs time scatter plotStack Overflow