javascript - d3 折线图任意线填充

标签 javascript d3.js

我正在尝试使用 d3 创建一个简单的折线图,但由于某种原因,它会在线和某个中点之间填充。这是输出:

Line Chart

我的 javascript 如下:

        var width = 500,
            height = 500,
            padding = 10;

        var extentVisits = d3.extent(visits, function(obj){
            return obj['visits'];
        });

        var extentDates = d3.extent(visits, function(obj){
            return obj['datestamp'];
        });

        var yScale = d3.scale.linear()
            .domain(extentVisits)
            .range([height - padding, padding]);

        var xScale = d3.time.scale()
            .domain(extentDates)
            .range([0, width]);

        var line = d3.svg.line()
            .x(function(d) {
                return xScale(d['datestamp']);
            })
            .y(function(d) {
                return yScale(d['visits']);
            })

        d3.select('#chart')
            .append('svg')
            .attr('width', width)
            .attr('height', height)
            .append("g")
            .attr("transform", "translate(5,5)")
            .append('path')
            .datum(visits)
            .attr("class", "line")
            .attr('d', line);

访问的形式是:

        visits = [{'datestamp': timestampA, 'visits': 1000},
                  {'datestamp': timestampB, 'visits': 1500}]

我是 d3 的新手,所以我确信这很简单,但它让我抓狂。

提前致谢。

最佳答案

您看到的中点只是第一个点和最后一个点的连接点。这是因为您创建的路径(默认情况下)具有黑色填充。即使它是一条开放路径(即第一个点和最后一个点实际上并未连接),如果已填充,它将显示为闭合:

The fill operation fills open subpaths by performing the fill operation as if an additional "closepath" command were added to the path to connect the last point of the subpath with the first point of the subpath.

来源:SVG specification通过this SO answer

此处的解决方案是取消填充,而是设置描边。您可以直接在 JS 中使用 d3 或通过 CSS 执行此操作。

path.line
{
    fill: none;
    stroke: #000;
}

Demo showing both the CSS and JS method (commented out) on jsFiddle

关于javascript - d3 折线图任意线填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14765036/

相关文章:

javascript - 我应该如何将 Svelte Reactivity 与 DOM getElementById 一起使用?

javascript - dc.js 获取折线图分组后的值

javascript - JavaScript 中的随机数生成和嵌套数组

javascript - 在 d3 图表上为每个节点级别添加事件监听器

javascript - 如何在 Web Audio API 中正确取消当前更改的 AudioParam

javascript - 将数据从请求对象传递到模板node.js

javascript - 是否可以在 CSS3 中的元素之间创建线条?

javascript - 是否可以更改 Plotly Js 气泡图悬停工具提示中的文本?

javascript - 无法使用 d3 仅在 "rect "内显示一次 X 轴值

JavaScript 对象对于所有版本的 Google Chrome 都是唯一的?