【问题标题】:Different bar data x-axis using D3.js使用 D3.js 的不同条形数据 x 轴
【发布时间】:2020-10-27 11:13:42
【问题描述】:

因为我是 D3.js 图表的新手。我发现了一些有用的东西,因为我想根据我的客户规范对其进行转换。下面是我用作示例的代码。

<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style type="text/css">
    svg {
        font: 10px sans-serif;
        shape-rendering: crispEdges;
    }

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

    path.domain {
        stroke: none;
    }

    .y .tick line {
        stroke: #ddd;
    }
</style>

<script type="text/javascript">

        // Setup svg using Bostock's margin convention

        var margin = { top: 20, right: 160, bottom: 35, left: 30 };

        var width = 960 - margin.left - margin.right,
            height = 500 - margin.top - margin.bottom;

        var svg = d3.select("body")
            .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 + ")");


        /* Data in strings like it would be if imported from a csv */

        var data = [
            { year: "2006", redDelicious: "10", mcintosh: "15", oranges: "9", pears: "6" },
            { year: "2007", redDelicious: "12", mcintosh: "18", oranges: "9", pears: "4" },
            { year: "2008", redDelicious: "05", mcintosh: "20", oranges: "8", pears: "2" },
            { year: "2009", redDelicious: "01", mcintosh: "15", oranges: "5", pears: "4" },
            { year: "2010", redDelicious: "02", mcintosh: "10", oranges: "4", pears: "2" },
            { year: "2011", redDelicious: "03", mcintosh: "12", oranges: "6", pears: "3" },
            { year: "2012", redDelicious: "04", mcintosh: "15", oranges: "8", pears: "1" },
            { year: "2013", redDelicious: "06", mcintosh: "11", oranges: "9", pears: "4" },
            { year: "2014", redDelicious: "10", mcintosh: "13", oranges: "9", pears: "5" },
            { year: "2015", redDelicious: "16", mcintosh: "19", oranges: "6", pears: "9" },
            { year: "2016", redDelicious: "19", mcintosh: "17", oranges: "5", pears: "7" },
        ];

        var datatable = {
            "dataTable": "Monthly cash flow estimate",
            "graph": "c1",
            "income": [
                { "Rent": 1340.00 },
                { "Internet": 40.00 }
            ],
            "expenses": [
                { "Mortgage repayment": 720.00 },
                { "Maintenance": 135.00 },
                { "Taxes": 127.00 },
                { "Other expenses": 50.00 },
                { "Insurance": 45.00 }
            ]
        };

        var parse = d3.time.format("%Y").parse;


        // Transpose the data into layers
        var dataset = d3.layout.stack()(["redDelicious", "mcintosh", "oranges", "pears"].map(function (fruit) {
            return data.map(function (d) {
                return { x: parse(d.year), y: +d[fruit] };
            });
        }));


        // Set x, y and colors
        var x = d3.scale.ordinal()
            .domain(dataset[0].map(function (d) { return d.x; }))
            .rangeRoundBands([10, width - 10], 0.02);

        var y = d3.scale.linear()
            .domain([0, d3.max(dataset, function (d) { return d3.max(d, function (d) { return d.y0 + d.y; }); })])
            .range([height, 0]);

        var colors = ["b33040", "#d25c4d", "#f2b447", "#d9d574"];


        // Define and draw axes
        var yAxis = d3.svg.axis()
            .scale(y)
            .orient("left")
            .ticks(5)
            .tickSize(-width, 0, 0)
            .tickFormat(function (d) { return d });

        var xAxis = d3.svg.axis()
            .scale(x)
            .orient("bottom")
            .tickFormat(d3.time.format("%Y"));

        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis);

        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis);


        // Create groups for each series, rects for each segment
        var groups = svg.selectAll("g.cost")
            .data(dataset)
            .enter().append("g")
            .attr("class", "cost")
            .style("fill", function (d, i) { return colors[i]; });

        var rect = groups.selectAll("rect")
            .data(function (d) { return d; })
            .enter()
            .append("rect")
            .attr("x", function (d) { return x(d.x); })
            .attr("y", function (d) { return y(d.y0 + d.y); })
            .attr("height", function (d) { return y(d.y0) - y(d.y0 + d.y); })
            .attr("width", x.rangeBand())
            .on("mouseover", function () { tooltip.style("display", null); })
            .on("mouseout", function () { tooltip.style("display", "none"); })
            .on("mousemove", function (d) {
                var xPosition = d3.mouse(this)[0] - 15;
                var yPosition = d3.mouse(this)[1] - 25;
                tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
                tooltip.select("text").text(d.y);
            });


        // Draw legend
        var legend = svg.selectAll(".legend")
            .data(colors)
            .enter().append("g")
            .attr("class", "legend")
            .attr("transform", function (d, i) { return "translate(30," + i * 19 + ")"; });

        legend.append("rect")
            .attr("x", width - 18)
            .attr("width", 18)
            .attr("height", 18)
            .style("fill", function (d, i) { return colors.slice().reverse()[i]; });

        legend.append("text")
            .attr("x", width + 5)
            .attr("y", 9)
            .attr("dy", ".35em")
            .style("text-anchor", "start")
            .text(function (d, i) {
                switch (i) {
                    case 0: return "Anjou pears";
                    case 1: return "Naval oranges";
                    case 2: return "McIntosh apples";
                    case 3: return "Red Delicious apples";
                }
            });


        // Prep the tooltip bits, initial display is hidden
        var tooltip = svg.append("g")
            .attr("class", "tooltip")
            .style("display", "none");

        tooltip.append("rect")
            .attr("width", 30)
            .attr("height", 20)
            .attr("fill", "white")
            .style("opacity", 0.5);

        tooltip.append("text")
            .attr("x", 15)
            .attr("dy", "1.2em")
            .style("text-anchor", "middle")
            .attr("font-size", "12px")
            .attr("font-weight", "bold");

    </script>

并给出如下输出。

因为我在下面有这些数据,需要在 x 轴上显示为不同的条形,如上所示,并且它们之间也需要有间隙。一个例子是这样的 income 代替 JanRent & Internet 作为具有 gap 的条形数据和以此类推 费用 代替 Feb 与另一个栏

var data = {            
            "income": [
                { "Rent": 1340.00 },
                { "Internet": 40.00 }
            ],
            "expenses": [
                { "Mortgage repayment": 720.00 },
                { "Maintenance": 135.00 },
                { "Taxes": 127.00 },
                { "Other expenses": 50.00 },
                { "Insurance": 45.00 }
            ]
        };

这是一个固定的对象数据,如月份、MobileCoupon、Bonus 等,我上面的数据不是固定的,我想在条形图上使用。

var data = [
            { month: "Jan", MobileCoupon: "430000", Bonus: "240000", Promotions: "200000", Merchandise: "150000" },
            { month: "Feb", MobileCoupon: "250000", Bonus: "440000", Promotions: "200000", Merchandise: "150000" },
            { month: "Mar", MobileCoupon: "350000", Bonus: "180000", Promotions: "200000", Merchandise: "150000" },
        ];

在 x 轴条形图上附加不同数据对象的任何帮助将不胜感激。

【问题讨论】:

    标签: javascript d3.js bar-chart


    【解决方案1】:

    找到问题的解决方案。

    var data = [
                { "Type": "2006", "Rent": "1340.00", "Internet": "40.00", "Mortgage repayment": "0.00", "Maintenance": "0.00", "Taxes": "0.00", "Other expenses": "0.00", "Insurance": "0.00" },
                { "Type": "2007", "Rent": "0", "Internet": "0", "Mortgage repayment": "720.00", "Maintenance": "135.00", "Taxes": "127.00", "Other expenses": "50.00", "Insurance": "45.00" }
            ];
    
    var dataset = d3.layout.stack()(["Rent", "Internet", "Mortgage repayment", "Maintenance", "Taxes", "Other expenses", "Insurance"].map(function (fruit) {
                return data.map(function (d) {
                    return { x: parse(d.Type), y: +d[fruit] };
                });
            }));
    

    刚刚制作了 0 ,这不是必需的。只需要在 20062007 的位置加上 incomeexpenses。并且需要堆叠条之间的间隙

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多