Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

javascript - How to use scaleTime to horizontally position a background rectangle

I want to have the d3 js chart with a different background rectangle based on some timestamps.

var orangeBack = svg
  .append("rect")
  .attr("x", margin.left + 0)
  .attr("y", margin.top)
  .attr("height", containerHeight - 120)
  .attr("width", 200)
  .style("stroke", bordercolor)
  .attr("fill", "orange")
  .attr("opacity", 0.2)
  .style("stroke-width", border);

I have a d3 js chart created per below:

enter image description here

My code sandbox - https://codesandbox.io/s/quizzical-bhabha-4ullr?file=/src/TimelineChart.js

Right now I have given 200 in width but this will be my timestamp in x scale.

.attr("width", 200)

How I can use x scale for horizontally positioning the rectangle by timestamp ?

.attr("width", xScale()) // or XDomain something.. 

I tried to use scale e.g. but it's not working.

  var orangeBack = svg.selectAll("rect")   
    .data(data)
    .enter()
    .append("rect")
    //.attr("x", margin.left + 0)
    .attr("x", function(d){return xScale(d.startTime)})
    .attr("y", margin.top)
    .attr("height", containerHeight - 120)
    // .attr("width",  200)
    .attr("width", function(d){return (xScale(d.startTime) - xScale("1568283720049"));})
    .style("stroke", bordercolor)
    .attr("fill", "orange")
    .attr("opacity", 0.05)
    .style("stroke-width", border);

Any reference will be helpful. Thanks..

I am trying to follow something like this.. How to add background shading to D3 line chart

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is how I am trying to achieve this. Let me know if anything better we can do.

var orangeBack = svg
  .selectAll("rect")
  .data(data)
  .enter()
  .append("rect")
  .attr("x", margin.left)
  // .attr("x", function (d) {
  //   return xScale(1568283720049);
  // })
  .attr("y", margin.top)
  .attr("height", containerHeight - 120)
  // .attr("width",  200)
  .attr("width", function (d) {
    return xScale(1568283720049) - xScale(1567851720049) + 10;
  })
  .style("stroke", bordercolor)
  .attr("fill", "orange")
  .attr("opacity", 0.05)
  .style("stroke-width", border);

currently I have given the timestamp directly e.g. xScale(1568283720049) this can be done dynamically.

code sandbox - https://codesandbox.io/s/quizzical-bhabha-4ullr?file=/src/TimelineChart.js


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...