Javascript-Plotly.js编号频率顺序

时间:2018-07-26 14:57:29

标签: javascript plotly

我有一个plot.ly,它输入数字和数字来查看频率数。每说一次,您输入111222333和数字1,2,3。它将显示每个数字重复的条形图。除了一个细节,其他所有内容似乎都可以正常使用,只要我添加随机数,图形就不会按顺序显示。 Here is an example

下面是我的JS代码:

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});

}

1 个答案:

答案 0 :(得分:1)

您正在categoryorder: 'category ascending'中使用layout,而在Plotly中的直方图不存在。截至2018年7月,您无法按直方图对分类数据进行排序。但是只需将数组排序然后再传递给Plotly即可。

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>