简体   繁体   English

负值未显示在分组的条形图中

[英]Negative values not showing in grouped bar chart

I am trying to make a grouped bar chart with negative and positive values. 我正在尝试制作带有负值和正值的分组条形图。 The problem is that I can only draw the positive values. 问题是我只能得出正值。 The Y-axis stops at 0 instead of at the lowest value. Y轴从0停止而不是最低值。 How can I make sure the bar chart can have positive and negative values at the same time? 如何确保条形图可以同时具有正值和负值?

This is my CSV: 这是我的CSV:

name,value,koken,kcal
Ab,-15,0,-7
C,22,1,2
Bc,-20,0,-10
E,2,1,20

And this is my code: 这是我的代码:

var margin = {top: 20, right: 30, bottom: 40, left: 30},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

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

var x0 = d3.scaleBand()
    .rangeRound([0, width]);

var x1 = d3.scaleBand()
    .padding(0.05);

var y = d3.scaleLinear()
    .rangeRound([height, 0]);

var z = d3.scaleOrdinal()
    .range(["#98abc5", "#8a89a6", "#7b6888"]);

d3.csv("flare0.csv", function(d, i, columns) {
    for (var i = 1, n = columns.length; i < n; ++i) d[columns[i]] = +d[columns[i]];
    return d;
},
    function(error, data) {
    if (error) throw error;

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

    x0.domain(data.map(function(d) { 
        return d.name; }));

        x1.domain(keys).rangeRound([0, x0.bandwidth()]);

    y.domain([0, d3.max(data, function(d) { return d3.max(keys, function(key) { return d[key]; }); })]).nice();

  console.log(data);
    g.append("g")
        .selectAll("g")
        .data(data)
        .enter().append("g")
        .attr("class", function(d) { return d < 0 ? "bar negative" : "bar positive"; })
            .attr("transform", function(d) { return "translate(" + x0(d.name) + ",0)"; })
        .selectAll("rect")
        .data(function(d) { return keys.map(function(key) { return {key: key, value: d[key]}; }); })
        .enter().append("rect")
        .attr("x", function(d) { return x1(d.key); })
        .attr("y", function(d) { return y(d.value); })
        .attr("width", x1.bandwidth())

        .attr("height", function(d) {
            console.log(height - y(d.value));
            return height - y(d.value); })
        .attr("fill", function(d) { return z(d.key); });

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

    g.append("g")
        .attr("class", "axis")
        .call(d3.axisLeft(y).ticks(null, "0"))
        .append("text")
        .attr("x", 20)
        .attr("y", y(y.ticks().pop()) + 0.5)
        .attr("dy", "0.32em")
        .attr("fill", "#000")
        .attr("font-weight", "bold")
        .attr("text-anchor", "start")
        .text("Population");       
});

This gist provides an example that may get you closer. 本要点提供了一个示例,可以使您更加接近。 By adding the following code, I've managed to get both negative annd positive values to appear together: 通过添加以下代码,我设法使两个负值和正值一起出现:

 y.domain([
    d3.min(data, function(d) { return d3.min(keys, function(key) { return d[key]; }); }),
    d3.max(data, function(d) { return d3.max(keys, function(key) { return d[key]; }); })]).nice();

Here's a updated Plunker: http://plnkr.co/edit/pZzFKaiQWNVJm0SuK9kW?p=preview 这是更新的Plunker: http ://plnkr.co/edit/pZzFKaiQWNVJm0SuK9kW?p=preview

If you use the gist I provided as a reference, you'll be able to modify your code so that the bars are drawn from 0, rather than the lowest value. 如果您使用我提供的要点作为参考,则可以修改代码,以便从0(而不是最低)绘制条形图。

First, change your y scale domain to get the negative values: 首先,更改您的y标度域以获取负值:

y.domain([d3.min(data, function(d) {
    return d3.min(keys, function(key) {
        return d[key];
    });
}), d3.max(data, function(d) {
    return d3.max(keys, function(key) {
        return d[key];
    });
})]).nice();

If you want a shorter code, consider using d3.extent here. 如果需要较短的代码,请考虑在此处使用d3.extent

Then, change your math: it makes no sense the bars coming from the base of the axis and going up. 然后,改变数学:从轴的根部向上延伸的条形没有意义。 Instead of that, all bars should come from the 0 value in the y axis, and go up if they are positive, otherwise go down if they are negative: 取而代之的是,所有条形图都应从y轴的0值开始,如果它们为正数则上升,否则为负数:

.attr("y", function(d) {
    return d.value > 0 ? y(d.value) : y(0);
})
.attr("height", function(d) {
    return d.value > 0 ? y(0) - y(d.value) : y(d.value) - y(0);
})

Here is your code with those changes: 这是您所做的更改的代码:

 var csv = `name,value,koken,kcal Ab,-15,0,-7 C,22,1,2 Bc,-20,0,-10 E,2,1,20`; var margin = { top: 20, right: 30, bottom: 40, left: 30 }, width = 600 - margin.left - margin.right, height = 400 - margin.top - margin.bottom; var svg = d3.select("svg"), g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var x0 = d3.scaleBand() .rangeRound([0, width]); var x1 = d3.scaleBand() .padding(0.05); var y = d3.scaleLinear() .rangeRound([height, 0]); var z = d3.scaleOrdinal() .range(["#98abc5", "#8a89a6", "#7b6888"]); var data = d3.csvParse(csv, function(d, i, columns) { for (var i = 1, n = columns.length; i < n; ++i) d[columns[i]] = +d[columns[i]]; return d; }); var keys = data.columns.slice(1); x0.domain(data.map(function(d) { return d.name; })); x1.domain(keys).rangeRound([0, x0.bandwidth()]); y.domain([d3.min(data, function(d) { return d3.min(keys, function(key) { return d[key]; }); }) * 1.1, d3.max(data, function(d) { return d3.max(keys, function(key) { return d[key]; }); }) * 1.1]).nice(); g.append("g") .selectAll("g") .data(data) .enter().append("g") .attr("class", function(d) { return d < 0 ? "bar negative" : "bar positive"; }) .attr("transform", function(d) { return "translate(" + x0(d.name) + ",0)"; }) .selectAll("rect") .data(function(d) { return keys.map(function(key) { return { key: key, value: d[key] }; }); }) .enter().append("rect") .attr("x", function(d) { return x1(d.key); }) .attr("y", function(d) { return d.value > 0 ? y(d.value) : y(0); }) .attr("width", x1.bandwidth()) .attr("height", function(d) { return d.value > 0 ? y(0) - y(d.value) : y(d.value) - y(0); }) .attr("fill", function(d) { return z(d.key); }); g.append("g") .attr("class", "axis") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x0)); g.append("g") .attr("class", "axis") .call(d3.axisLeft(y).ticks(null, "0")) .append("text") .attr("x", 20) .attr("y", y(y.ticks().pop()) + 0.5) .attr("dy", "0.32em") .attr("fill", "#000") .attr("font-weight", "bold") .attr("text-anchor", "start") .text("Population"); 
 <script src="https://d3js.org/d3.v4.min.js"></script> <svg width="600" height="400"></svg> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM