Adam Tomeček
Adam Tomeček

Reputation: 209

D3.js fill part of graph with background

I have a basic line chart with two lines like this

line chart

I want to apply background in part where only blue line is to highlight part where both lines are. What is the best way to do this in D3.js?

Part of my code

x = d3.time.scale()
  .domain([date_from, date_to])
  .range([0, width])

y = d3.scale.linear()
  .domain([15, 30])
  .range([height, 0])

line = d3.svg.line()
  .x((d, i) -> x(parseDate(d.date)))
  .y((d) -> y(d.price))

svg = d3.select("#graph").append("svg:svg")
  .attr("width", width + 50)
  .attr("height", height + 50)
  .append("svg:g")
  .attr("transform", "translate(25, 25)")

svg.append("svg:g")
  .attr("class", "x axis")
  .attr("transform", "translate(0, #{height})")
  .call(xAxis)

svg.append("svg:g")
  .attr("class", "grid")
  .attr("transform", "translate(0, #{height})")
  .call(xAxis.tickSize(-height, 0, 0).tickFormat("").ticks(80))

svg.append("svg:g")
  .attr("class", "grid")
  .call(yAxis.tickSize(-width, 0, 0).tickFormat("").ticks(40))

svg.append("svg:path")
  .attr("class", "line")
  .attr("d", line(data))
  .style("stroke", (d) -> color("year"))

svg.append("svg:path")
  .attr("class", "line")
  .attr("d", line(data2))
  .style("stroke", (d) -> color("month"))

Upvotes: 2

Views: 3723

Answers (1)

ninjaPixel
ninjaPixel

Reputation: 6382

Draw a rect element on that portion of the chart.

var rectangle = svg.append("rect")
                    .attr("x", 0)
                    .attr("y", 0)
                    .attr("width", x(firstXValueOfSecondLine))
                    .attr("height", chartHeight)
                    .style('opacity', 0.5)
                    .style('fill', '#ededed');

Upvotes: 4

Related Questions