Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...