Home > Software engineering >  How to set a varying opacity of dots in a D3 scatter plot
How to set a varying opacity of dots in a D3 scatter plot

Time:03-13

So I made this scatter plot using D3 with dots for each datapoint.

svg.append("g")
  .selectAll("dot")
  .data(data)
  .enter()
  .append("circle")
  .attr("cx", function(d) {
    return xScale(d.PC);
  })
  .attr("cy", function(d) {
    return yScale(d.TRIN_NORM);
  })
  .attr("r", 2)
  .attr("opacity", 1.0)      // HERE JUST SET OVERALL OPACITY
  .style("fill", "Blue")

Here is a picture of the chart:

Scatter Plot

The columns PC and TRIN_NORM are both 1000 entries.

Now I would like the opacity of each circle to vary according to its position in the array. For instance have the opacity vary from i=0 to 999 such that:

opacity(i) = 0.05   (1.0-0.05)/999 * i

The opacity varies from 0.05 to 1.0 for the last data point.

How can i achieve this? I am only a beginner in javascript & D3, so any help would be greatly appreciated.

====

I managed to change the colours of the circles as well, as suggested below

                .attr("opacity", function(d, i) {
                    return 0.05   (1.0 - 0.05) / 999 * i;
                })
                .style("fill", function(d, i) {
                    return d3.interpolatePlasma((999 - i) / 999);
                })

CodePudding user response:

In the function signature for the opacity attribute (and others) you can use function(d, i) instead of function(d) where i is the index of the element of data in the selection.

Since you know the formula you want it's just:

.attr("opacity", function(d, i) {
  return 0.05   (1.0-0.05)/999 * i;
})

Here's an example with 10 circles (and therefore 9 instead of 999 in the example):

// svg
const svg = d3.select("body")
  .append("svg")
  .attr("width", 320)
  .attr("height", 100);

// sample array
let data = [];
for (let i=0; i<10; i  ) {
  data.push({"name": "dot_"   i, "someProperty": "someValue"});
}

// 10 dots in a line with opactiy linked to index
svg.append("g")
  .selectAll("dot")
  .data(data)
  .enter()
  .append("circle")
  .attr("cx", function(d, i) {
    //return xScale(d.PC);
    return (i * 28)   16;
  })
  .attr("cy", function(d) {
    //return yScale(d.TRIN_NORM);
    return 50;
  })
  .attr("r", 12)
  .attr("opacity", function(d, i) {
    //return 100;
    return  0.05   (1.0 - 0.05) / 9 * i
  })
  .style("fill", "Blue")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

  • Related