3

and thanks for your time.

I would like to do this that you can see in the picture.

chartJs line graph

I have the values for the labels in array and values for the yAxes in other array. The labels show the 59 minutes of the hour, and i want to show only the minutes (05, 10, 15, 20 .....etc) I can push in the array only this time values, but then when i put the "times" in the labels in chartjs, the chart only show 12 values in yAxes, and i want to show the 59 values in yAxes and only this xAxes...

if i do this:

  import { Fragment } from "react";
  import { Line } from "react-chartjs-2";
 import "./GraficosDemo.css";

const GraficosDemo = ({ datosMeteoGraf, rotuloGrafico }) => {
var colors = [
"#007bff",
"#0097fc",
"#333333",
"#c3e6cb",
"#dc3545",
"#ed872d",
];
if (!datosMeteoGraf) return null;

const dataSetTWS = [];
const dataSetTWS_GUST = [];
const minutos = [];

 //GRAFICO DE INTENSIDAD DE VIENTO
  for (let i = 0; i < datosMeteoGraf.length; i++) {    
    dataSetTWS.push(datosMeteoGraf.TWS[i]);    
     }

 //GRAFICO DE INTENSIDAD DE RACHAS DE VIENTO
   for (let i = 0; i < datosMeteoGraf.length; i++) {    
     dataSetTWS_GUST.push(datosMeteoGraf.TWS_GUST[i]);  
   }
    // console.log(dataSetTWS_GUST);

    for (let i = 0; i < datosMeteoGraf.length; i++) {         
     if((new Date (datosMeteoGraf.TIME[i]).getMinutes()) % 5 === 0){
  minutos.push(new Date(datosMeteoGraf.TIME[i]).toTimeString().slice(0, 5))
   }        
   }


  return (
    <Fragment>
      <Line
        data={{
       labels: minutos,
      datasets:[
        {
          borderWidth: 0,
          label: "Intensidad Última Hora",
          data: dataSetTWS,
          backgroundColor: "transparent",
          borderColor: colors[1],
          pointStyle: "dash",
        },          
        {
          borderWidth: 0,
          label: "Intensidad Rachas de Viento",
          data: dataSetTWS_GUST,
          backgroundColor: "transparent",
          borderColor: colors[4],
          pointStyle: "dash",
        },
      ],
    }}
    height={250}
    options={{
      maintainAspectRatio: false,
      scales: {
        yAxes: [
          {
            ticks: {
              beginAtZero: true,
              stepSize: 1,
            },
          },
        ],
        xAxes: [
          {
            display:true,
          }
        ]
      },
    }}
  />

  
</Fragment>
  );
 };

export default GraficosDemo;

i have this:

push in time array only the minutes multiples of 5

But i would like to keep all my values and show only this labels. Like in the picture at the top.

Could someone help me please? Thanks

ddaudiosolutions
  • 131
  • 2
  • 15

2 Answers2

2

ChartJS does not need labels to map the values. The good way to do what you are doing is to implement a time axis. This would allow you to add any range of time without adding to the list of labels. You also need a time parser. here is a list.

config:

const config = {
  type: 'line',
  data: data,
  options: { 
      scales: {
          xAxis: {
                type: 'time',
                
                ticks: {
                    source: 'labels', // get ticks from given labels
                },

                time: {
                    minUnit: 'minute', // smallest time format

                    displayFormats: {
                        minute: "HH:mm",
                        hour: "dd/MM HH:mm",
                        day: "dd/MM",
                        week: "dd/MM",
                        month: "MMMM yyyy",
                        quarter: 'MMMM yyyy',
                        year: "yyyy",
                    }
                }
            },
        },
    }
};

data:

var data = {
  labels: labels,
  datasets: [{
    label: 'My First Dataset',
    data: generateTestSeries(),
    fill: false,
    borderColor: 'rgb(75, 192, 192)',
    tension: 0.1
  }]
};

labels:

var labels = [
  new Date(2021, 10, 15, 15, 0),
  new Date(2021, 10, 15, 15, 5),
  new Date(2021, 10, 15, 15, 10),
  new Date(2021, 10, 15, 15, 15),
  new Date(2021, 10, 15, 15, 20),
  new Date(2021, 10, 15, 15, 25),
  new Date(2021, 10, 15, 15, 30),
  new Date(2021, 10, 15, 15, 35),
  new Date(2021, 10, 15, 15, 40),
  new Date(2021, 10, 15, 15, 45),
  new Date(2021, 10, 15, 15, 50),
  new Date(2021, 10, 15, 15, 55),
  new Date(2021, 10, 15, 16, 0),
];

test data:

function generateTestSeries () { // create test data
    let series = [];
    var val = 0;

    let start = new Date(2021, 10, 15, 15);
    let end = new Date(2021, 10, 15, 16);

    while (start < end) {
        val += Math.floor(Math.random() * 11) - 5;

        series.push({
            "x": start, 
            "y": val, 
        });

        start = new Date(start.getTime() + 60000);
    }
    
    return series;
}

this will look like: enter image description here

as for my previous point about the labels, you can drop them and it will generate some based on your data. it will look like this: enter image description here

if that's okay you can do it by removing labels: labels,

and changing source: 'labels', to source: 'auto',

for more on time axes: Time Cartesian Axis

Jesper
  • 1,007
  • 7
  • 24
  • If chart.js does not need labels to map the values to why are you using labels to map the values to instead of only providing a data array? – LeeLenalee Oct 29 '21 at 09:36
  • @LeeLenalee The 1st graph is with labels and the 2nd graph is without them. 1st one being more customizable and 2nd one being easier to make and more flexible. – Jesper Oct 29 '21 at 09:45
  • Both are using labels, only difference is that in the first chart you provide them in the labels array while in the second one you provide them as an object where X is the label and Y is the value – LeeLenalee Oct 29 '21 at 09:47
  • Like how you say it I should be able to pass only an array of numbers but then chart.js would have no knowledge on what to do with those numbers so how you put it doesn't matter chartjs needs labels to map values to and visualize them – LeeLenalee Oct 29 '21 at 09:48
  • @LeeLenalee I guess better wording would have been "you don't have to give the labels." If `source: auto` creates labels from my data under the hood, i don't really care. I don't have to deal with them and that's all that matters to me. – Jesper Oct 29 '21 at 10:04
1

Chart.js needs labels to map the values to so you will need to provide labels, although you can use the tick callback to hide some of the labels like so:

var options = {
  type: 'line',
  data: {
    labels: ["0", "5", "10", "15", "20", "25"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      xAxes: [{
        ticks: {
          callback: (tick) => (Number(tick) % 10 === 0 ? tick : null) // Replace null with "" to show gridline
        }
      }]
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69