【问题标题】:D3.js is it possible to draw circles on each point using nested data?D3.js 是否可以使用嵌套数据在每个点上绘制圆圈?
【发布时间】:2020-10-21 18:44:53
【问题描述】:

我有一个需要渲染的图表,它有多条线。有单独的点和一条穿过它们的线。在每一点上,我想画一个圆圈。对于线条,我正在使用 d3.nest() 函数将 csv 文件转换为数据数组,然后使用我提供的键进行嵌套,并在每个点上绘制圆圈,我只是使用原始数据' 大批。我想知道的是,有没有办法使用 NESTED 数组作为输入在点上绘制圆圈?还是我必须使用原始数据文件在每个点上绘制圆圈?

【问题讨论】:

  • 请分享一些 ypu 目前正在做的代码,以便我们更好地指导您。

标签: javascript d3.js


【解决方案1】:

当然可以。如果您在嵌套数据集中为每个组创建一个“组”,那么您可以为每个组绘制一条线,并为每个组中的每个点绘制一个圆圈。看看以下内容:

const fruits = ["Apples", "Oranges", "Bananas"];
const colors = ["red", "orange", "yellowgreen"];
const rawData = fruits.map((obj, f) => {
  let v = 1;
  return d3.range(30).map(i => ({
    fruit: f,
    index: i,
    value: v *= (0.95 + Math.random() * 0.1)
  }));
}).flat();

const nestedData = d3.nest()
  .key(d => d.fruit)
  .entries(rawData);

const width = 800,
  height = 200;

const x = d3.scaleLinear()
  .domain([0, 29])
  .range([0, width]);

const y = d3.scaleLinear()
  .domain(d3.extent(rawData, d => d.value))
  .range([height, 0])
  .nice();

const color = d3.scaleOrdinal()
  .domain(fruits)
  .range(colors);

const line = d3.line()
  .x(d => x(d.index))
  .y(d => y(d.value));

const svg = d3.select("svg")
  .attr("width", width)
  .attr("height", height);

const lineGroup = svg.selectAll(".line-group")
  .data(nestedData)
  .enter()
  .append("g")
  .attr("class", "line-group");

lineGroup.append("path")
  .datum(d => d.values)
  .attr("class", "line")
  .attr("stroke", d => color(d[0].fruit))
  .attr("d", line);

lineGroup.selectAll("circle")
  .data(d => d.values)
  .enter()
  .append("circle")
  .attr("class", "dot")
  .attr("stroke", d => color(d.fruit))
  .attr("r", 5)
  .attr("cx", d => x(d.index))
  .attr("cy", d => y(d.value));
.line {
  fill: none;
  stroke-width: 2px;
}

.dot {
  stroke-width: 2px;
  fill: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>

【讨论】:

    猜你喜欢
    • 2015-05-17
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    相关资源
    最近更新 更多