1

I have line chart and method that is filling it with data, but i want to display only last 10 points in the chart.

getRandomInt() {
this.intervalId = setInterval(() => {
  this.setState(prevState => {
    return {
      chartData: {
        ...prevState.chartData,
        labels: [
          ...prevState.chartData.labels,
          prevState.chartData.labels.length + 1,
        ],
        datasets: [
          {
            ...prevState.chartData.datasets[0],
            data: [
              ...prevState.chartData.datasets[0].data,
              Math.floor(Math.random() * 10) + 1,
            ],
          },
        ],
      },
    };
  });
}, 2000);}

Is there a weay to do it?

2
  • 5
    You could use data: [ ... ].slice(-10) to give the last 10 elements of the array to the data property.
    – Tholle
    Commented Feb 22, 2019 at 12:34
  • Thats how i end up doing it at the end. I was hoping there is a way of doing it in Chartjs options. Commented Feb 22, 2019 at 13:59

1 Answer 1

0

If you want to display only top 10 and leave other option visible only in legend. You can try:

const datasets = [
  ...top10.map(item => ({
    label: item.label,
    data: item.data,
    borderWidth: 2
  })),
  ...others.map(item => ({
    label: item.label,
    data: [], // Hidden from chart
    borderWidth: 0,
    hidden: true
  }))
];

It was working for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.