samedi 26 décembre 2015

D3JS - Display both circles and triangles in a scatter plot

I have a dataset displayed on a D3JS scatter plot. Basically, points of the dataset are (x, y, category) and I would like to plot "Category A" as orange circles and "Category B" as blue triangles.

[TODAY] colors are ok but all points are circles :

[ ... ]
      var color = d3.scale.ordinal()
          .domain(["Category A", "Category B"])
          .range(["#f76800", "#000066"]);

  // draw dots
  svg.selectAll(".dot")
      .data(data)
    .enter().append("circle")
      .attr("class", "dot")
      .attr("r", 7)
      .attr("cx", xMap)
      .attr("cy", yMap)
      .style("fill", function(d) {
           return color(d.category);
      ;})
[ ... ]

I found this thread Triangle scatter plot with D3.js so I was trying - with not much success - something like :

[ ... ]
      var color = d3.scale.ordinal()
          .domain(["Category A", "Category B"])
          .range(["#f76800", "#000066"]);

  // draw dots
  svg.selectAll(".dot")
      .data(data)
    .enter().append((d.category == "Category A") ? "circle":"path")
      .attr((d.category == "Category A") ? "CIRCLE attr":"TRIANGLE attr")
      .style("fill", function(d) {
           return color(d.category);
      ;})
[ ... ]

Is it a reasonable try ?

EDIT : Attempt

[ ... ]
  svg.selectAll(".dot")
      .data(data)
    .enter().append((d.category == "A") ? "path":"circle")
    .attr((d.category=="A") ? ({"d":d3.svg.symbol().type("triangle-up"), "transform":"translate(" + xMap + "," + yMap + ")"}):({"class":"dot", "r":7, "cx":xMap, "cy":yMap}))
      .style("fill", function(d) {
           return color(d.category);
      ;})
      .style("opacity", .95 )
      .style("stroke-width", function(d) {
            if (d.category == "A") {return 0.95}
            else { return 0 }
      ;})
[ ... ]

Result : "ReferenceError : d is undefined" in Firebug console

Edit 2 - data subset

May this help : to see the full code, here is the actual website : http://ift.tt/1J9AK3Z . Note that field "d.category" mentioned here for educational purpose, is in fact "d.site".

Data subset : Data come from a MySQL request, fields include : "prix" (for Y value), "date" (for X value), and "site" i.e. category above. Other fields are irrelevant here. Please find a data subset here : http://ift.tt/1OlWJkm




Aucun commentaire:

Enregistrer un commentaire