【问题标题】:d3 : coloring dots on a scatterplot using column in datasetd3:使用数据集中的列在散点图上着色点
【发布时间】:2021-10-29 08:00:10
【问题描述】:

我已经复制了一些代码来制作基本的散点图,并且我正在尝试根据其中一列数据为点着色。

我尝试将数据集修改为具有一个名为“Color”的列,其值介于 0 和 1 之间,但是当我分配颜色函数(即 d3.interpolateRdGy(d[2]) )时,散点图上没有点.

我对 d3 非常非常陌生(我只有在 R 中使用 ggplot2 的经验)。

<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>

<script>

// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 60},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

//Read the data
d3.csv("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/2_TwoNum.csv", function(data) {

  // Add X axis
  var x = d3.scaleLinear()
    .domain([0, 4000])
    .range([ 0, width ]);

  svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

  // Add Y axis
  var y = d3.scaleLinear()
    .domain([0, 500000])
    .range([ height, 0]);

  svg.append("g")
    .call(d3.axisLeft(y));

  // Add dots
  svg.append('g')
    .selectAll("dot")
    .data(data)
    .enter()
    .append("circle")
      .attr("cx", function (d) { return x(d.GrLivArea); } )
      .attr("cy", function (d) { return y(d.SalePrice); } )
      .attr("r", 1.5)
      .style("fill",  d3.interpolateRdGy(d[1]))

})

</script>

【问题讨论】:

  • 您需要将其包装在一个函数中才能访问绑定的数据d:.style("fill", d =&gt; d3.interpolateRdGy(d[1]))

标签: html svg d3.js colors


【解决方案1】:

通常使用 D3,您将创建一个色标。如果您想将定量值映射到颜色,那么您可以这样做

const color = d3.scaleSequential()
    .domain(d3.extent(data, d => d.Color))
    .interpolator(d3.interpolateBlues);

d3.extent(data, d =&gt; d.Color) 返回一个数组,其中包含数据集中“颜色”列的最小值和最大值。与直接调用插值器不同,即使值不在 0 和 1 之间,这种方法也可以工作。

您可以在d3-scale-chromatic docs 中找到其他配色方案。对于不同的配色方案,您可以使用diverging scale

然后要使用色标,你会这样做

    .attr('fill', d => color(d.Color))

【讨论】:

    猜你喜欢
    • 2014-03-09
    • 2016-11-20
    • 2021-07-03
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多