Plotly.js Bar Charts Automatically Order the X-Axis Values
When I build a bar chart while my data are dynamic, I want to be able to reorder the x value array so that the y values can be shown corresponding with the appropritate x value.
For exampe, an array of [1,2,3,4,5] for x-axis and [10,5,3,7,9] for y-axis looks like this:
WHen Data is Dynamic
When data is dynamic, the x values are created randomly. Either I need to use other algorithem to reorder the x array and create y arrray corresponding it, or Plotly.js takes care of the reordering work.
For exampe, an array of [2,1,4,5,3] for x-axis and [5,10,9,3,7] for y-axis looks like this, which looks exactly the same with the one above, because x-y value pairs are reorganized from small to big:
The problem of counting random numbers
With Ployly.js' automatic array reordering mechenism, couting random numbers are easy. Here, the order of random numbers matter, otherwise we don't even need to reorder them. Now I want to count random intergers from 1 to 100 created by Math.random()
function count(){
//create a random interger ranged from 1 to 100.
var randomNumber = Math.ceil(Math.random()*100);
//checking if the random number exists in the x value array.
var index = xValues.findIndex(x=>x == randomNumber)
if(index == -1){
//if randomNumber is not in the x value array, the index will be -1;
xValues.push(randomNumber);
yValues.push(1);
}else{
yValues[index]++;
};
};
Comments
Post a Comment