如何确保D3条形图的条在响应式时不会移开其刻度?

huangapple go评论75阅读模式
英文:

How do I ensure D3 bar plot bars don't move away from their ticks while being responsive?

问题

我尝试在D3中创建一个条形图,显示负值和正值。我已经编写了代码来实现这个目标,但是我遇到了一个问题,矩形不正确地放置在x轴上。例如,1880年的矩形位于1880年刻度的右侧几个间隙。此外,代表2000年的条形图位于x轴上的1990年左右。理想情况下,我希望图表能够响应屏幕的空间,但确保条形图不会远离它们的刻度。

我曾假设.rangeBoundBands会均匀分布它们,但看起来还有其他一些问题没有解决。非常感谢任何人可以提供的帮助。以下是您的代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Land Ocean Temperature Index</title>
    <!-- // <script type="text/javascript" src="../d3.v3.js"></script> -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
    <style type="text/css">
        html, body, * {
            font-family: Arial, sans-serif;
            text-align: center;
            font-size: 14px 65%;
        }

        .bar.positive {
            fill: darkred;
        }

        .bar.negative {
            fill: steelblue;
        }

        g.infowin {
            fill: grey;
        }

        g.infowin text,
        .axis text {
            font: 11px sans-serif;
            fill: grey;
        }

        .axis path,
        .axis line {
            fill: none;
            stroke: #000;
            shape-rendering: crispEdges;
        }

        path.domain {
            stroke: none;
        }
    </style>
</head>
<body>
<div id="chart"></div>
<script type="text/javascript">
    var margin = {
        top: 10,
        right: 10,
        bottom: 20,
        left: 30
    },
    width = window.innerWidth - margin.left - margin.right,
    height = window.innerHeight - margin.top - margin.bottom;

    var y = d3.scale.linear()
    .range([height, 0]);

    var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .2);

    var xAxisScale = d3.scale.linear()
    .domain([1880, 2015])
    .range([0, width]);

    var xAxis = d3.svg.axis()
    .scale(xAxisScale)
    .orient("bottom")
    .tickFormat(d3.format("d"));

    var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

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

    d3.csv("https://gist.githubusercontent.com/djr-taureau/d3599e17a3f1c5089a10e26dac9aee03/raw/a43e610d8b1c99bc17b8789b5641b84f243871b1/Land-Ocean-TempIndex-YR.csv", type, function(error, data) {
    x.domain(data.map(function(d) {
        return d.Year;
    }));
    y.domain(d3.extent(data, function(d) {
        return d.Celsius;
    })).nice();

    svg.selectAll(".bar")
        .data(data)
        .enter().append("rect")
        .attr("class", function(d) {

            if (d.Celsius < 0){
                return "bar negative";
            } else {
                return "bar positive";
            }

        })
        .attr("data-yr", function(d){
            return d.Year;
        })
        .attr("data-c", function(d){
            return d.Celsius;
        })
        .attr("title", function(d){
            return (d.Year + ": " + d.Celsius + " °C")
        })
        .attr("y", function(d) {

            if (d.Celsius > 0){
                return y(d.Celsius);
            } else {
                return y(0);
            }

        })
        .attr("x", function(d) {
            return x(d.Year);
        })
        .attr("width", x.rangeBand())
        .attr("height", function(d) {
            return Math.abs(y(d.Celsius) - y(0));
        })
        .on("mouseover", function(d){
            // alert("Year: " + d.Year + ": " + d.Celsius + " Celsius");
            d3.select("#_yr")
                .text("Year: " + d.Year);
            d3.select("#degrree")
                .text(d.Celsius + "°C");
        });

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

    svg.append("g")
        .attr("class", "y axis")
        .append("text")
        .text("°Celsius")
        .attr("transform", "translate(15, 40), rotate(-90)")

    svg.append("g")
        .attr("class", "X axis")
        .attr("transform", "translate(" + (margin.left - 6.5) + "," + height + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "x axis")
        .append("line")
        .attr("y1", y(0))
        .attr("y2", y(0))
        .attr("x2", width);

    svg.append("g")
        .attr("class", "infowin")
        .attr("transform", "translate(50, 5)")
        .append("text")
        .attr("id", "_yr");

    svg.append("g")
        .attr("class", "infowin")
        .attr("transform", "translate(110, 5)")
        .append("text")
        .attr("id","degrree");
    });

    function type(d) {
    d.Celsius = +d.Celsius;
    return d;
    }
</script>
</body>
</html>

如果您需要进一步的帮助或有其他问题,请随时告诉我。

英文:

I am trying to create a bar plot in D3 that displays negative and positive values. The code I have does this however I have an issue with the rectangle not sitting correctly on the x-Axis. For example the rectangle for the year 1880 sits a few spaces to the right of the 1880 tick. Also the bar representing 2000 sits around the 1990 mark on the x-Axis. Ideally I want the chart to be able to fill the space of the screen responsively but ensure the bars dont move away from their ticks.

I had assumed that .rangeBoundBands would space it out evenly but it looks like there is something else that's not quite working. Would really appreciate any help that anybody could offer. Code below:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;title&gt;Land Ocean Temperature Index&lt;/title&gt;
&lt;!-- // &lt;script type=&quot;text/javascript&quot; src=&quot;../d3.v3.js&quot;&gt;&lt;/script&gt; --&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js&quot;&gt;&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
html, body, * {
font-family: Arial, sans-serif;
text-align: center;
font-size: 14px 65%;
}
.bar.positive {
fill: darkred;
}
.bar.negative {
fill: steelblue;
}
g.infowin {
fill: grey;
}
g.infowin text,
.axis text {
font: 11px sans-serif;
fill:grey;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
path.domain {
stroke:none;
}
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id=&quot;chart&quot;&gt;&lt;/div&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var margin = {
top: 10,
right: 10,
bottom: 20,
left: 30
},
width = window.innerWidth - margin.left - margin.right,
height = window.innerHeight - margin.top - margin.bottom;
var y = d3.scale.linear()
.range([height, 0]);
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .2);
var xAxisScale = d3.scale.linear()
.domain([1880, 2015])
.range([0, width]);
var xAxis = d3.svg.axis()
.scale(xAxisScale)
.orient(&quot;bottom&quot;)
.tickFormat(d3.format(&quot;d&quot;));
var yAxis = d3.svg.axis()
.scale(y)
.orient(&quot;left&quot;);
var svg = d3.select(&quot;#chart&quot;).append(&quot;svg&quot;)
.attr(&quot;width&quot;, width + margin.left + margin.right)
.attr(&quot;height&quot;, height + margin.top + margin.bottom)
.append(&quot;g&quot;)
.attr(&quot;transform&quot;, &quot;translate(&quot; + margin.left + &quot;,&quot; + margin.top + &quot;)&quot;);
d3.csv(&quot;https://gist.githubusercontent.com/djr-taureau/d3599e17a3f1c5089a10e26dac9aee03/raw/a43e610d8b1c99bc17b8789b5641b84f243871b1/Land-Ocean-TempIndex-YR.csv&quot;, type, function(error, data) {
x.domain(data.map(function(d) {
return d.Year;
}));
y.domain(d3.extent(data, function(d) {
return d.Celsius;
})).nice();
svg.selectAll(&quot;.bar&quot;)
.data(data)
.enter().append(&quot;rect&quot;)
.attr(&quot;class&quot;, function(d) {
if (d.Celsius &lt; 0){
return &quot;bar negative&quot;;
} else {
return &quot;bar positive&quot;;
}
})
.attr(&quot;data-yr&quot;, function(d){
return d.Year;
})
.attr(&quot;data-c&quot;, function(d){
return d.Celsius;
})
.attr(&quot;title&quot;, function(d){
return (d.Year + &quot;: &quot; + d.Celsius + &quot; &#176;C&quot;)
})
.attr(&quot;y&quot;, function(d) {
if (d.Celsius &gt; 0){
return y(d.Celsius);
} else {
return y(0);
}
})
.attr(&quot;x&quot;, function(d) {
return x(d.Year);
})
.attr(&quot;width&quot;, x.rangeBand())
.attr(&quot;height&quot;, function(d) {
return Math.abs(y(d.Celsius) - y(0));
})
.on(&quot;mouseover&quot;, function(d){
// alert(&quot;Year: &quot; + d.Year + &quot;: &quot; + d.Celsius + &quot; Celsius&quot;);
d3.select(&quot;#_yr&quot;)
.text(&quot;Year: &quot; + d.Year);
d3.select(&quot;#degrree&quot;)
.text(d.Celsius + &quot;&#176;C&quot;);
});
svg.append(&quot;g&quot;)
.attr(&quot;class&quot;, &quot;y axis&quot;)
.call(yAxis);
svg.append(&quot;g&quot;)
.attr(&quot;class&quot;, &quot;y axis&quot;)
.append(&quot;text&quot;)
.text(&quot;&#176;Celsius&quot;)
.attr(&quot;transform&quot;, &quot;translate(15, 40), rotate(-90)&quot;)
svg.append(&quot;g&quot;)
.attr(&quot;class&quot;, &quot;X axis&quot;)
.attr(&quot;transform&quot;, &quot;translate(&quot; + (margin.left - 6.5) + &quot;,&quot; + height + &quot;)&quot;)
.call(xAxis);
svg.append(&quot;g&quot;)
.attr(&quot;class&quot;, &quot;x axis&quot;)
.append(&quot;line&quot;)
.attr(&quot;y1&quot;, y(0))
.attr(&quot;y2&quot;, y(0))
.attr(&quot;x2&quot;, width);
svg.append(&quot;g&quot;)
.attr(&quot;class&quot;, &quot;infowin&quot;)
.attr(&quot;transform&quot;, &quot;translate(50, 5)&quot;)
.append(&quot;text&quot;)
.attr(&quot;id&quot;, &quot;_yr&quot;);
svg.append(&quot;g&quot;)
.attr(&quot;class&quot;, &quot;infowin&quot;)
.attr(&quot;transform&quot;, &quot;translate(110, 5)&quot;)
.append(&quot;text&quot;)
.attr(&quot;id&quot;,&quot;degrree&quot;);
});
function type(d) {
d.Celsius = +d.Celsius;
return d;
}
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

答案1

得分: 1

将柱形图的中心对齐到刻度上,从柱形图的 x 坐标中减去其一半宽度:

attr("x", function(d) {
  return x(d.Year) - x.rangeBand() / 2;
})
.attr("width", x.rangeBand())
英文:

To make center of a bar right on the tick, subtract its half-width from the bar's x coordinate:

attr(&quot;x&quot;, function(d) {
return x(d.Year) - x.rangeBand() / 2;
})
.attr(&quot;width&quot;, x.rangeBand())

huangapple
  • 本文由 发表于 2023年5月24日 23:38:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76325251.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定