d3:在表格中附加标题/标题

时间:2017-10-30 13:07:30

标签: javascript html css d3.js

我使用d3.js生成了一个表。但不知怎的,我无法在表格中添加标题或标题。我已经尝试追加.append(“text”),但它会位于表格下方。我最近的尝试是.append('caption'),这也行不通。 代码如下:

    ====================================================*/

// Get the data
data.forEach(function(d) {
  d.Timestamp = parseDate(d.Timestamp);
  d.Position = +d.Position;
  d.Agency = +d.Agency;
});

function tabulate(data, columns) {
  var table = d3.select(".grid_intent").append("table").append("caption").text("Table");
  thead = table.append("thead"),
    tbody = table.append("tbody");
  // append the header row
  thead.append("tr")
    .selectAll("th")
    .data(columns)
    .enter()
    .append("th")
    .text(function(column) {
      return column;
    });
  // create a row for each object in the data
  var rows = tbody.selectAll("tr").data(data)
    .enter()
    .append("tr");
  // create a cell in each row for each column
  var cells = rows.selectAll("td").data(function(row) {
      return columns.map(function(column) {
        return {
          column: column,
          value: row[column]
        };
      });
    })
    .enter()
    .append("td")
    .attr("style", "font-family: Courier")
    .attr("colspan", "2")
    .html(function(d) {
      return d.value;
    });
  return table;
}

// render the table
var Pos_All_Agen = tabulate(data, ["Agentur", "Position"])
//Sort Table Accoring to Position
Pos_All_Agen.selectAll("tbody tr")
  .sort(function(a, b) {
    return d3.ascending(a.Position, b.Position);
  });

1 个答案:

答案 0 :(得分:0)

你应该创造一个工作小提琴,以便我们可以正确测试,但在盲人中,试试这个:

// Get the data
data.forEach(function(d) {
  d.Timestamp = parseDate(d.Timestamp);
  d.Position = +d.Position;
  d.Agency = +d.Agency;
});

function tabulate(data, columns) {
  var table = d3.select(".grid_intent");
  var caption = table.append("caption").text("Table");
  table.append("table");
  thead = table.append("thead"),
    tbody = table.append("tbody");
  // append the header row
  thead.append("tr")
    .selectAll("th")
    .data(columns)
    .enter()
    .append("th")
    .text(function(column) {
      return column;
    });
  // create a row for each object in the data
  var rows = tbody.selectAll("tr").data(data)
    .enter()
    .append("tr");
  // create a cell in each row for each column
  var cells = rows.selectAll("td").data(function(row) {
      return columns.map(function(column) {
        return {
          column: column,
          value: row[column]
        };
      });
    })
    .enter()
    .append("td")
    .attr("style", "font-family: Courier")
    .attr("colspan", "2")
    .html(function(d) {
      return d.value;
    });
  return table;
}

// render the table
var Pos_All_Agen = tabulate(data, ["Agentur", "Position"])
//Sort Table Accoring to Position
Pos_All_Agen.selectAll("tbody tr")
  .sort(function(a, b) {
    return d3.ascending(a.Position, b.Position);
  });