簡體   English   中英

如何在 D3 散點圖中設置不同的點透明度 plot

[英]How to set a varying opacity of dots in a D3 scatter plot

所以我使用 D3 制作了這個散點圖 plot,每個數據點都有點。

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")

這是圖表的圖片:

散點圖

PC 和 TRIN_NORM 列都是 1000 個條目。

現在我希望每個圓圈的不透明度根據其在數組中的 position 而變化。 例如,不透明度從 i=0 到 999 不等,這樣:

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

最后一個數據點的不透明度從 0.05 到 1.0 不等。

我怎樣才能做到這一點? 我只是 javascript & D3 的初學者,所以任何幫助將不勝感激。

====

我也設法改變了圓圈的顏色,如下所示

                .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);
                })

在不透明度屬性(和其他屬性)的 function 簽名中,您可以使用function(d, i)而不是function(d) ,其中i是選擇中data元素的索引。

因為您知道您想要的公式,所以它只是:

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

這是一個包含 10 個圓圈的示例(因此示例中是 9 個而不是 999 個):

 // 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM