在d3版本4中使用序数比例创建散点图

时间:2017-01-26 09:50:59

标签: javascript d3.js

我正在尝试使用d3 v4创建散点图。我已经通过v3和v4的许多示例,但没有多少解释如何在v4中创建具有序数比例的图形。我的代码如下:

const margin = { top: 100, right: 50, left: 50, bottom: 50};
const width = 1500 - margin.right - margin.left;
const height = 1250 - margin.top - margin.bottom;

d3.csv("http://localhost:9000/data.csv", (error, data) => {
    if (error) throw error;

    const x = (d) => d["Category"];

    const xScale = d3.scaleOrdinal()
                     .domain(data.map((d) => d["Category"]))
                     .range([0, width]);


    const xAxis = d3.axisBottom(xScale);

    const y = (d) => d["Score"];
    const yScale = d3.scaleLinear()
                     .range([height, 0]);
    yScale.domain([d3.min(data, y)-1, d3.max(data, y)+1]);

    const yAxis = d3.axisLeft(yScale);

    const svg = d3.select('body')
                  .append('svg')
                  .attr('width', width)
                  .attr('height', height)
                  .append('g')
                  .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');


    svg.append('g')
       .attr('class', 'x axis')
       .call(xAxis)
       .attr('transform', 'translate(0, 400)')
       .append('text')
       .attr('class', 'label')
       .attr('x', width)
       .attr('y', -6)
       .style('text-anchor', 'end')
       .text('Category');

    svg.append('g')
       .attr('class', 'y axis')
       .call(yAxis)
       .attr('class', 'label')
       .attr('transform', 'rotate(-90)')
       .attr('y', 6)
       .attr('dy', '.71rem')
       .text('Score');

    svg.selectAll('circle')
       .data(data)
       .enter()
       .append('circle')
       .attr('class', 'dot')
       .attr('cx', (d) => {
           console.log(x(d));
           return x(d);
       })
       .attr('cy', (d) => y(d))
       .attr('r', 5)
       .attr('fill', 'red');
});

CSS:

.axis path,
.axis line {
    fill: none;
    stroke: grey;
    stroke-width: 1;
    shape-rendering: crispEdges;
}

我的问题是没有任何东西真正出现。我为每个我希望按顺序显示的x值得到此错误消息:

Error: <circle> attribute cx: Expected length, "B10".

y轴根本不显示,x轴显示没有刻度和“类别”文本。请帮忙!

1 个答案:

答案 0 :(得分:2)

这里不要使用scaleOrdinal,因为你有一个连续的范围。

请改用scalePoint。根据API:

  

点标度是带标度的变体,带宽固定为零。点标度通常用于具有序数或分类维度的散点图。

因此,它应该是:

const xScale = d3.scalePoint()
    .domain(data.map((d) => d["Category"]))
    .range([0, width]);

除此之外,您应该使用比例来设置cx属性,而不是“x”const:

.attr('cx', (d) => xScale(d.Category))