我有一个从CSV读取的堆积面积图。但是它不能正确渲染x轴和图形。

我试图更改x轴值,但没有帮助。

以下是示例CSV文件。

当前,该视图显示y轴值,右侧显示药物名称,但不显示实际堆积图或日期x轴值。

到目前为止return x(d.data.date)=返回NaN。

非常感谢你的帮助!

date,drug,market_share
2016-01-01,insulin lispro,.01
2016-01-01,alogliptin,0.001323754341
2016-01-01,sitagliptin,.01
2016-01-01,canagliflozin,0.02842158621
2016-01-01,glimepiride,0.05668845799
2016-01-01,repaglinide,0.0005768749342
2016-01-01,insulin glargine,.01
2016-01-01,metformin,0.4972895171
2016-01-01,mifepristone,.02
2016-01-01,exenatide,.02
2016-01-01,bromocriptine,0.0002109506723
2016-01-01,pioglitazone,0.02324500184
2016-01-01,metformin hydrochloride,0.392074889
2016-02-01,saxagliptin,.02
2016-02-01,pioglitazone,0.02247815103
2016-02-01,exenatide,0.03
2016-02-01,repaglinide,0.0006204220565
2016-02-01,metformin hydrochloride,0.394153624
2016-02-01,sitagliptin,.08
2016-02-01,insulin lispro,.05
2016-02-01,canagliflozin,0.02907988245
2016-02-01,metformin,0.4933502396
2016-02-01,insulin glargine,.02
2016-02-01,bromocriptine,0.0002076549233
2016-02-01,mifepristone,.02
2016-02-01,alogliptin,0.001364306972
2016-02-01,glimepiride,0.05857620484
2016-03-01,canagliflozin,0.02908102306
2016-03-01,bromocriptine,0.000195238081
2016-03-01,metformin,0.4966376769
2016-03-01,alogliptin,0.00133532899
2016-03-01,insulin glargine,.03
2016-03-01,sitagliptin,.04



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

<body>
<div id="div1"></div>
<div id="div2"></div>
</body>

<script src="https://d3js.org/d3.v4.js"></script>
<script>
    var parseDate = d3.timeParse("%Y-%m-%d");

    function type2(d, i, columns) {
        d.date = parseDate(d.date);
        return d;
    }

    function type(d, i, columns) {
        d.date = parseDate(d.date);
        for (var i = 1, n = columns.length; i < n; ++i) d[columns[i]] = d[columns[i]] / 100;
        return d;
    }

    function drawGraph(error, data, selector, width, height) {
        console.log("DATA "+selector+JSON.stringify(data));
        console.log("COL "+selector+"---"+data.columns);
        var svg = d3.select(selector).append("svg")
                .attr("width", width)
                .attr("height", height),
            margin = {top: 20, right: 20, bottom: 30, left: 50},
            width = svg.attr("width") - margin.left - margin.right,
            height = svg.attr("height") - margin.top - margin.bottom;


        var x = d3.scaleTime().range([0, width]),
            y = d3.scaleLinear().range([height, 0]),
            z = d3.scaleOrdinal(d3.schemeCategory10);

        var stack = d3.stack();

        var area = d3.area()
            .x(function (d, i) {
                return x(d.data.date);
            })
            .y0(function (d) {
                return y(d[0]);
            })
            .y1(function (d) {
                return y(d[1]);
            });

        var g = svg.append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        var keys = data.columns.slice(1);

        x.domain(d3.extent(data, function (d) {
            return d.date;
        }));

        z.domain(keys);
        stack.keys(keys);

        console.log("Stacked Data "+ selector+"---" + JSON.stringify(stack(data)));

        var layer = g.selectAll(".layer")
            .data(stack(data))
            .enter().append("g")
            .attr("class", "layer");

        layer.append("path")
            .attr("class", "area")
            .style("fill", function (d) {
                return z(d.key);
            })
            .attr("d", area);

        layer.filter(function (d) {
            return d[d.length - 1][1] - d[d.length - 1][0] > 0.01;
        })
            .append("text")
            .attr("x", width - 6)
            .attr("y", function (d) {
                return y((d[d.length - 1][0] + d[d.length - 1][1]) / 2);
            })
            .attr("dy", ".35em")
            .style("font", "10px sans-serif")
            .style("text-anchor", "end")
            .text(function (d) {
                return d.key;
            });

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

        g.append("g")
            .attr("class", "axis axis--y")
            .call(d3.axisLeft(y).ticks(10, "%"));
    }

    d3.csv("market_shares.csv", type2, function (error, data) {
        let stackedByDate = {}
        let drugSet = new Set();
        let defaultDrugMarketShareProp = {};
        let newData = []

        data.forEach(function (item, index) {
            drugSet.add(item.drug);
            stackedByDate[item.date] = {};
        });

        let drugNames = [...drugSet];

        drugNames.forEach(function (item, index) {
            defaultDrugMarketShareProp[item] = 0;
        });

        data.forEach(function (item, index) {
            stackedByDate[item.date] = Object.assign({}, defaultDrugMarketShareProp);
        });

        data.forEach(function (item, index) {
            stackedByDate[item.date][item.drug] = item.market_share;
        });

        Object.keys(stackedByDate).forEach(function (key) {
            hash = {}
            hash['date'] = key;
            Object.keys(stackedByDate[key]).forEach(function (innerKey) {
                hash[innerKey] = stackedByDate[key][innerKey]
            });

            newData.push(hash);
        });

        newData.columns = drugNames;
        newData.columns.unshift('date');

        drawGraph(error, newData, "#div2", 960, 500);
    });

</script>

最佳答案

您正确地分析了日期字符串。但是,在此功能中...

Object.keys(stackedByDate).forEach(function (key) {
    hash = {}
    hash['date'] = key;//<----- HERE
    Object.keys(stackedByDate[key]).forEach(function (innerKey) {
        hash[innerKey] = stackedByDate[key][innerKey]
    });
    newData.push(hash);
});


...您正在将日期对象再次转换回字符串。

最快的解决方案是:

hash['date'] = new Date(key);


这只是您所做的更改的代码:https://bl.ocks.org/GerardoFurtado/e9538de82e96cc9e3efb5fc4c7b9b970/5ca6920405243c39b93d0245230b955c37c85a2c

关于javascript - 堆积面积图未呈现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56281611/

10-08 23:06