gpt4 book ai didi

javascript - Y 轴已创建但不可见

转载 作者:太空宇宙 更新时间:2023-11-03 18:01:08 24 4
gpt4 key购买 nike

我用 D3.js 创建了一个简单的条形图,代码如下

<!DOCTYPE html>
<html>
<head>
<title>Bar Transition Example</title>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>

</head>
<body>

<script type="text/javascript">

var margin = {top: 20, right: 20, bottom: 30, left: 60},
width = 300 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;

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

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

var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");

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

data = [{"label":"apples","value":6000},{"label":"pears","value":5000},{"label":"bananas","value":4000}]


function bars(data)
{

x.domain(data.map(function(d) { return d.label; }));
y.domain([0, d3.max(data, function(d) { return d.value; })]);

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

d3.select("svg").append('g')
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".90em")
.style("text-anchor", "end");

bars = d3.select("svg").selectAll(".bar")
.data(data)

//enter
bars.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.label); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); });

}


function init()
{

//setup the svg
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 + ")");

bars(data)
}

init();
</script>

</body>
</html>

但我的 Y 轴并不像我预期的那样可视化。的确, Y轴被创建 enter image description here

我尝试调整所有参数(包括边距变量

var margin = {top: 20, right: 20, bottom: 30, left: 60},
width = 300 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;

但没有效果。

最佳答案

您需要翻译将包含轴的组:

d3.select("svg").append('g')
.attr('transform', 'translate(' + [margin.left, margin.top] + ')')
.attr("class", "y axis")
.call(yAxis);

轴被绘制在 SVG 元素之外。您可能还想翻译另一组。问候,

关于javascript - Y 轴已创建但不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25467487/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com