user2367509
user2367509

Reputation: 11

area(data) works but area does not d3.js

I am trying to create an area graph in d3.js. I wrote the following function:

  @drawAreaChart = (element,chart_value)->
console.log("Im in")
height=400              
data=chart_value
chart_area=d3.select(element)
area = d3.svg.area().x( (d) -> 
  return d.x 
)
.y0(height)
.y1( (d) ->          
  return height-d.y
).interpolate("linear")
line = d3.svg.line().x( (d) -> 
  return d.x
)
.y( (d) ->          
  return height-d.y
).interpolate("linear")
chart_area.selectAll(".line").data(data).enter().append("path").attr("d",line(data)).attr("class","line").attr("fill","none").attr("stroke","rgb(100,153,255)").attr("stroke-width",2)    
chart_area.selectAll(".area").data(data).enter().append("path").attr("d",area(data)).attr("class",".area").attr("fill","url(#gradient-effect)")    
return

The chart_value is being passed the following data:

      charts.drawAreaChart("#area-graph",[{"x":0,"y":100},
                                      {"x":100, "y":200},
                                      {"x":200,"y":250},
                                      {"x":300, "y":300},
                                      {"x":400, "y":230},
                                      {"x":500, "y":260},
                                      {"x":600, "y":160}]);

The function is within a charts module hence charts.drawAreaChart is being called. Now the problem is, the above code works for static data. I haven't tested for dynamic data. However if I use

chart_Area.selectAll(".area").data(data).enter().append("path").attr("d",area)

instead of

chart_Area.selectAll(".area").data(data).enter().append("path").attr("d",area(data))

the chart does not appear. The same happens with my line graph but in another function I create an arc and there i do not need to write it as attr("d",arc(data))

Upvotes: 1

Views: 846

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109242

D3's .data() function expects an array of items, each of which represents one of the DOM elements that you've been selecting (in your case .area). You're passing in an array of points, which means that D3 matches each point to a new DOM element. So the area function is being passed a single point.

When you call area(data) explicitly in this context, you're actually get several areas -- one per point.

To make this work without giving the argument explicitly, pass in the area data as an array, i.e.

chart_Area.selectAll(".area").data([data]).enter().append("path").attr("d",area);

Upvotes: 1

Related Questions