【问题标题】:Assign different colours to vertical lines in a line chart based on property value根据属性值为折线图中的垂直线分配不同的颜色
【发布时间】:2020-10-16 15:08:56
【问题描述】:

我想创建一个折线图,其中有两条垂直线标记一连串高值 (10) 的开始(红色)和结束(绿色)。这些行的颜色应根据输出变量中的 start_end 属性指定,如下所示:

关于如何实现这一目标的任何想法?这是我目前的代码(我使用的是 d3 v6)

{
  const svg = d3.select(DOM.svg(width, height))
  
  svg.append('g').call(xAxis)
  svg.append('g').call(yAxis)
 
  svg.append("line")
        .datum(output)
        .attr("d", line)
        .attr("fill", "none")
        .style("stroke", "steelblue")
        .style("stroke-width", 4)
        .attr("stroke-linejoin", "round")
        .attr("stroke-linecap", "round")
        .attr("x1", xScale(output.timestamp))
        .attr("y1", 0)
        .attr("x2", xScale(output.timestamp))
        .attr("y2", 10)
        
  svg.append('path')
      .datum(segment)
      .attr('d', line)
      .style('fill', 'none')
      .style('stroke', 'black')  
  
  return svg.node()
}

output = [
  {timestamp: "2020-09-25T04:00:54.857Z", jam_factor: 10, start_end: "start"}
  {timestamp: "2020-09-29T18:02:23.282Z", jam_factor: 8.39212, start_end: "end"}
]

【问题讨论】:

  • 您使用的是什么版本的 d3?当有多个条纹时会发生什么?
  • 抱歉忘了提,我使用的是版本 6

标签: javascript d3.js charts line


【解决方案1】:

我生成了一些数据,并在下面展示了如何以通用方式添加开始和停止线。

const data = [0, 3, 5, 7, 5, 4, 6, 7, 10, 10, 10, 10, 7, 5, 7, 6, 8, 9, 9, 10, 10, 10, 10, 10, 10, 9, 5, 6, 4, 6, 8, 10, 10, 9].map((v, i) => {
  const now = new Date();
  now.setDate(i);
  return {
    timestamp: now,
    value: v,
  };
});

// Find all places where we first hit or stop hitting 10
let active = false;
data.forEach((d, i) => {
  if (d.value === 10) {
    if (!active) {
      d.start = true;
      active = true;
    }
  } else {
    // The previous was the last active one
    if (active) {
      data[i - 1].end = true;
      active = false;
    }
  }
});

const width = 600,
  height = 300;
const x = d3.scaleTime()
  .domain(d3.extent(data, d => d.timestamp))
  .range([0, width]);
const y = d3.scaleLinear()
  .domain([0, 10])
  .range([height - 10, 10]);
const line = d3.line()
  .x(d => x(d.timestamp))
  .y(d => y(d.value))

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

svg.append("path")
  .datum(data)
  .attr("d", line)
  .style("stroke", "steelblue")
  .style("stroke-width", 2)
  .style("fill", "none");

svg.selectAll("line")
  .data(data.filter(d => d.start || d.end))
  .enter()
  .append("line")
  .attr("x1", d => x(d.timestamp))
  .attr("x2", d => x(d.timestamp))
  .attr("y1", y.range()[0])
  .attr("y2", y.range()[1])
  .attr("stroke", d => d.start ? "green" : "red")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script>
<svg></svg>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多