moe
moe

Reputation: 71

Javascript - Plotly.js number frequency in order

I have a plot.ly that inputs a number and digits to view the number of frequency. Per say you enter 111222333 and digits 1,2,3. It will display a bar graph of the repetition of each digit. Everything seems to work except one detail, whenever I add random numbers, the graph does not display in order. Here is an example

Below is my JS code:

function plotIt() {
event.preventDefault();
var entireNumber = document.getElementById('fullNumber').value.split("");
var number = document.getElementById('digit').value.split("");
var matchedNumbers = [];

entireNumber.forEach(digit => {
if (number.includes(digit)) {
  matchedNumbers.push(digit);
}
});

var layout = {
categoryorder: 'category ascending',
xaxis: {
  type: 'category',
  title: 'Values',
},
yaxis: {
  title: '# of repetitions'
},
title:'Count'
};

var histElements = {
x: matchedNumbers,
type: 'histogram',
marker: {
  color: 'rgba(235, 77, 75,1.0);',
  },
};

var data = [histElements];
//Using ID for div to plot the graph
Plotly.newPlot('graph', data, layout,{scrollZoom:true});

}

Upvotes: 1

Views: 658

Answers (1)

Maximilian Peters
Maximilian Peters

Reputation: 31669

You are using categoryorder: 'category ascending' in layout which does not exist for histograms in Plotly. As of July 2018 you cannot sort categorical data in histograms. But simply sorting your array before passing it to Plotly should work.

function plotIt() {
  var entireNumber = document.getElementById('fullNumber').value.split("");
  var number = document.getElementById('digit').value.split("");
  number.sort();
  var matchedNumbers = [];

  entireNumber.forEach(digit => {
    if (number.includes(digit)) {
      matchedNumbers.push(digit);
    }
  });
  matchedNumbers.sort();

  var layout = {
    xaxis: {
      type: 'category',
      title: 'Values',
    }
  };

  var histElements = {
    x: matchedNumbers,
    type: 'histogram'
  };
  var data = [histElements];

  Plotly.newPlot('graph', data, layout);

}

var button = document.getElementById('button');
button.addEventListener("click", plotIt(), false);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<form>
  <input type='number' id='fullNumber' value='144445522123' >
  <input type='number' id='digit' value='0123456789'>
</form>
<button type="button" id='button'>Plot me!</button>

<div id='graph'>
</div>

Upvotes: 1

Related Questions