可以将动态 html 表用作源数据吗?

2022-01-21 00:00:00 plotly r r-markdown jquery javascript

如果我有一个 html 表,其中包含根据文件中的过滤器计算的值,我可以根据这些值读取并生成绘图吗?

If I have an html table that contains values that are calculated based on filters within my file, can I get plotly to read and produce a plot based on those values?

我不确定回答这个问题是否重要,但我主要使用 R,并使用 r 代码块从我使用 crosstalk 包创建的 sharedData 对象名称 shared_ert 计算总和为 R.

I'm not sure that it matters to answering this question, but I use R primarily, and use the r code chunks calculate sums from a sharedData object names shared_ert that I created with the crosstalk package for R.

<table id="example" class="cell-border" style="width:100%">
<tr>
<th>Enrolled</th>
<th>Not Enrolled</th>
</tr>
<tr>
<td>
```{r, echo=FALSE, collapse=TRUE, warning=FALSE, message=FALSE}
summarywidget::summarywidget(shared_ert,statistic = 'sum',column = 'Enrolled')
```
</td>
<td>

```{r, echo=FALSE, collapse=TRUE, warning=FALSE, message=FALSE}
summarywidget::summarywidget(shared_ert,statistic = 'sum',column = 'Not Enrolled')

```

</td>
</tr>
</table>

请注意,摘要小部件最终会在每个 td 中生成一个 span 标签.跨度看起来像

所以表格最终看起来像:

So the table ends up looking like:

<table id="example" class="cell-border" style="width:100%">
<tr>
<th>Enrolled</th>
<th>Not Enrolled</th>
</tr>
<tr>
<td>
<span id ="waffle" class="summarywidget html-widget html-widge-static-bound">1293</span>
<script type="application/json" data-for="waffle">
### a bunch of data appears here, from which the 1293 value is derived
</script>

</td>
<td>
<span id ="iron" class="summarywidget html-widget html-widge-static-bound">948</span>
<script type="application/json" data-for="iron">
### a bunch of data appears here, from which the 948 value is derived
</script>


</td>
</tr>
</table>

根据我对 javascript 世界的有限理解,我需要我的数据看起来像

From my limited understanding of the world of javascript, I need my data to look something like

var data = [
{
x: ['giraffes', 'orangutans', 'monkeys'],
y: [20, 14, 23],
type: 'bar'
  }
];

这样我就可以得到一个类似这样的情节:

So that I can get a plot produced with something like:

Plotly.newPlot('myDiv', data);

(直接来自 https://plotly.com/javascript/bar-charts/)

如果我正确理解了问题,我需要阅读 html 表 example 并创建一个保存该表的 var.经过大量搜索 SO 和一般网络后,我的猜测是这里的解决方案:HTML Table to JSON 将表格拉入正确的格式.我在努力

If I understand the problem correctly, I need to read the html table example and create a var that holds the table. After much searching around SO and the web in general, my guess is that the solution here: HTML Table to JSON pulls the table into the correct format. I'm trying

```{js}
function tableToJson(table) {
var data = [];

// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++) {
    headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}

// go through cells
for (var i=1; i<table.rows.length; i++) {

    var tableRow = table.rows[i];
    var rowData = {};

    for (var j=0; j<tableRow.cells.length; j++) {

        rowData[ headers[j] ] = tableRow.cells[j].innerHTML;

    }

    data.push(rowData);
}       

return data;
}

var tabdata = $document.getElementById('#example').tableToJSON();            

```

我想从这里开始,我需要在当前状态下从表中读取数据,所以我使用按钮和 onclick 生成绘图,如下所示:

I think from here, I need plotly to read the data from the table in it's current state, so I produce the plot using a button and onclick, as follows:

<button type="button" onclick="Plotly.newPlot('myDiv',tabdata);">Make Plot</button>

点击后,会出现绘图,但在任何地方都没有数据点.

Upon clicking, the plotly plot appears, but doesn't have a data point anywhere.

我的方法论可能偏离了轨道,所以我顺从最初的问题:我可以根据动态 html 表读取并生成绘图吗?

I might be way off track in my methodology, so I defer to the original question: can I get plotly to read and produce a plot based on a dynamic html table?

非常感谢任何帮助建立为此目的的方法.

Any help establishing a means to this end would be very much appreciated.

推荐答案

您需要生成带有键 x & 的 jsony .所以,这里 x 值将是您的标题,即: th 标签和 y 值将是 td值.现在,如果您的表中只有一行,您可以简单地创建 JSON 对象,然后使用键将值推入其中:data[x"]、data[y";]..等等.

You need generate your json with keys x & y .So , here x value will be your header i.e : th tags and y values will be tdvalues . Now , if you have only one row in your table you can simply create JSON Object and then push value inside this using key i.e : data["x"] , data["y"]..etc .

演示代码:

function tableToJSON(table) {
  var data = {}; //create obj
  data["x"] = [] //for x & y
  data["y"] = []
  data["type"] = "bar"
  for (var i = 0; i < table.rows[0].cells.length; i++) {
    data["x"].push(table.rows[0].cells[i].innerHTML.toLowerCase().trim()); //push x values
  }
  for (var i = 1; i < table.rows.length; i++) {
    var tableRow = table.rows[i];
    for (var j = 0; j < tableRow.cells.length; j++) {
      data["y"].push(parseInt(tableRow.cells[j].querySelector(".summarywidget").textContent.trim()));
      //push y values
      console.log(tableRow.cells[j].querySelector(".summarywidget").textContent.trim())
    }
  }

  return data;
}

function draw() {
  var tabdata = tableToJSON(document.getElementById('example'));
  tester = document.getElementById('tester');
  Plotly.newPlot(tester, [tabdata])
}

<script src="https://cdn.plot.ly/plotly-2.1.0.min.js"></script>
<table id="example" class="cell-border" style="width:100%">
  <tr>
    <th>Enrolled</th>
    <th>Not Enrolled</th>
  </tr>
  <tr>
    <td>
      <span id="waffle" class="summarywidget html-widget html-widge-static-bound">1293</span>
      <script type="application/json" data-for="waffle">
        ###
        a bunch of data appears here, from which the 1293 value is derived
      </script>

    </td>
    <td>
      <span id="iron" class="summarywidget html-widget html-widge-static-bound">948</span>
      <script type="application/json" data-for="iron">
        ###
        a bunch of data appears here, from which the 948 value is derived
      </script>


    </td>
  </tr>
</table>

<button type="button" onclick="draw()">Make Plot</button>
<div id="tester" style="width:600px;height:250px;"></div>

现在,如果您的表中有多行,则需要生成该值的 JSON 数组.为此,您需要保留 main_array 然后将值推送到其中每次迭代的 main_array.

Now , if you have mutliple rows in your table you need to generate JSON Array of that values .For that you need to keep main_array and then push values inside this main_array on each iterations.

演示代码:

function tableToJSON(table) {
  var main_array = [] //for main array
  var for_x = [] //for x values
  for (var i = 0; i < table.rows[0].cells.length; i++) {
    for_x.push(table.rows[0].cells[i].innerHTML.toLowerCase().trim()); //push value 
  }
  for (var i = 1; i < table.rows.length; i++) {
    var tableRow = table.rows[i];
    var data = {}; //create obj..
    data["y"] = [] //for y values
    for (var j = 0; j < tableRow.cells.length; j++) {
      data["y"].push(parseInt(tableRow.cells[j].innerHTML.trim())); //push y values
    }
    //save other values..
    data["x"] = for_x
    data["type"] = "bar"
    data["name"] = "Rows" + i
    main_array.push(data) //push values in main array
  }
  //console..[{},{}..]
  return main_array;

}

function draw() {
  var tabdata = tableToJSON(document.getElementById('example'));
  tester = document.getElementById('tester');
  //pass it here
  Plotly.newPlot(tester, tabdata, {
    barmode: 'stack'
  })
}

<script src="https://cdn.plot.ly/plotly-2.1.0.min.js"></script>
<table id="example" class="cell-border" style="width:100%">
  <tr>
    <th>Enrolled</th>
    <th>Not Enrolled</th>
  </tr>
  <tr>
    <td>
      123
    </td>
    <td>
      125
    </td>
  </tr>
  <tr>
    <td>
      121
    </td>
    <td>
      127
    </td>
  </tr>
</table>

<button type="button" onclick="draw()">Make Plot</button>
<div id="tester" style="width:600px;height:250px;"></div>

相关文章