简体   繁体   English

d3.js 示例代码中的“图表”如何工作?

[英]How does 'chart' work in d3.js example code?

Good day, I'm learning d3.js.美好的一天,我正在学习 d3.js。 I'm reading this candlestick-chart example: https://observablehq.com/@d3/candlestick-chart but its code confused me besause of its first part:我正在阅读这个烛台图表示例: https://observablehq.com/@d3/candlestick-chart但它的代码让我很困惑,因为它的第一部分:

chart = {
  const svg = d3.create("svg")
      .attr("viewBox", [0, 0, width, height]);

  svg.append("g")
      .call(xAxis);

  svg.append("g")
      .call(yAxis);

  const g = svg.append("g")
      .attr("stroke-linecap", "round")
      .attr("stroke", "black")
    .selectAll("g")
    .data(data)
    .join("g")
      .attr("transform", d => `translate(${x(d.date)},0)`);

  g.append("line")
      .attr("y1", d => y(d.low))
      .attr("y2", d => y(d.high));

  g.append("line")
      .attr("y1", d => y(d.open))
      .attr("y2", d => y(d.close))
      .attr("stroke-width", x.bandwidth())
      .attr("stroke", d => d.open > d.close ? d3.schemeSet1[0]
          : d.close > d.open ? d3.schemeSet1[2]
          : d3.schemeSet1[8]);

  g.append("title")
      .text(d => `${formatDate(d.date)}
Open: ${formatValue(d.open)}
Close: ${formatValue(d.close)} (${formatChange(d.open, d.close)})
Low: ${formatValue(d.low)}
High: ${formatValue(d.high)}`);

  return svg.node();
} 

Why did this example put the codes inside chart?为什么这个例子把代码放在图表里? What does the svg.node() do in this example? svg.node()在这个例子中做了什么? Thank you!谢谢!

That's not valid JavaScript, but an example of a "cell" in Observable's custom language (which is built on JavaScript):这不是有效的 JavaScript,而是 Observable 的自定义语言(基于 JavaScript 构建)中的“单元”示例:

https://observablehq.com/@observablehq/observables-not-javascript https://observablehq.com/@observablehq/observables-not-javascript

You can compare it to a normal function , but as a bonus, things that depend on each other are automatically recalculated when needed:您可以将其与普通的function进行比较,但作为奖励,需要时会自动重新计算相互依赖的事物:

https://observablehq.com/@observablehq/how-observable-runs https://observablehq.com/@observablehq/how-observable-runs

So in this case, chart is a "function" that creates a chart based on some data and other settings, and then returns the SVG element ( svg.node() ).所以在这种情况下, chart是一个“函数”,它根据一些data和其他设置创建图表,然后返回 SVG 元素( svg.node() )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM