Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
How to create multiple x-axis datasets labels by using chart.js

I'm using chart.js to draw line charts. and currently there is a need is to draw 3 different lines. they have same y-axis dataset, but the x-axis datasets are different. like:

y-axis datasets: [2,4,6,8,10]
x-axis1 datasets: [1,2,3,4,5]
x-axis2 datasets: [5,6,7,8,9]
x-axis3 datasets: [8,9,10,12,14]

I want the x-axis range is 1 to 14. and display them by each datasets real value.

however, I investigated and just found the way to use different x-axis labels by xAxisID, but in this way, the x-axis2 and x-axis3 are still using 1,2,3,4,5 as x-axis dataset.

Does anyone know how can I achieve this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This can be done by defining datasets.data as an array of objects having an x and y property each.

data: [
  { 'x': 1, 'y': 2 },
  { 'x': 2, 'y': 4 },
  { 'x': 3, 'y': 6 },
  { 'x': 4, 'y': 8 },
  { 'x': 5, 'y': 10 }
]

You can use Array.map() to easily convert your data. Please take a look at below runnable code and see how it works.

const y = [2, 4, 6, 8, 10];
const x1 = [1, 2, 3, 4, 5];
const x2 = [5, 6, 7, 8, 9];
const x3 = [8, 9, 10, 12, 14];

new Chart('myChart', {
  type: 'line',
  data: {
    datasets: [{
      label: 'A',
      data: y.map((v, i) => ({ x: x1[i], y: v })),
      borderColor: 'rgb(255, 0, 0)',
      backgroundColor: 'rgba(255, 0, 0, 0.2)'
    },
    {
      label: 'B',
      data: y.map((v, i) => ({ x: x2[i], y: v })),
      borderColor: 'rgb(0, 255, 0)',
      backgroundColor: 'rgba(0, 255, 0, 0.2)'
    },
    {
      label: 'C',
      data: y.map((v, i) => ({ x: x3[i], y: v })),
      borderColor: 'rgb(0, 0, 255)',
      backgroundColor: 'rgba(0, 0, 255, 0.2)'
    }]
  },
  options: {
    scales: {
      x: {
        type: 'linear',
        suggestedMin: 1,
        suggestedMax: 14,
        ticks: {
          stepSize: 1
        }
      },
      y: {
        beginAtZero: true
      }
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
<canvas id="myChart" height="80"></canvas>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda