gpt4 book ai didi

javascript - 如何在 D3.js 中解开 y 轴

转载 作者:行者123 更新时间:2023-11-28 19:00:58 26 4
gpt4 key购买 nike

我有一个尝试绘制 x 轴和 y 轴的脚本:

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

var x = d3.scale.ordinal()
.domain(["apple", "orange", "banana"])
.rangePoints([0, width]);

var xAxis = d3.svg.axis()
.scale(x)
.orient("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 + ")");

svg.append("g")
.attr("class", "x axis")
.call(xAxis);


var y = d3.scale.ordinal()
.domain(["1", "2", "3"])
.rangePoints([0, 3]);


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

svg.append("g")
.attr("class", "y axis")
.call(yAxis);
.axis text {
font: 10px sans-serif;
}

.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>

正如您在运行代码时所看到的,y 轴被挤压了。我怎样才能解开它?

最佳答案

您需要正确设置 y 范围

var y = d3.scale.ordinal()
.domain(["1", "2", "3"])
.rangePoints([height, 0]);
<小时/>

来自文档 ( https://github.com/mbostock/d3/wiki/Ordinal-Scales#ordinal_rangePoints ),

# ordinal.rangePoints(interval[, padding])

Sets the output range from the specified continuous interval. The array interval contains two elements representing the minimum and maximum numeric value. This interval is subdivided into n evenly-spaced points, where n is the number of (unique) values in the input domain.

您输入的域有 3 个值,您希望这些值在图表的高度上间隔开。

<小时/>

堆栈片段

您可能还想将 x 轴平移到底部(如果没有,只需恢复 x 轴上的平移)

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

var x = d3.scale.ordinal()
.domain(["apple", "orange", "banana"])
.rangePoints([0, width]);

var xAxis = d3.svg.axis()
.scale(x)
.orient("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 + ")");

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


var y = d3.scale.ordinal()
.domain(["1", "2", "3"])
.rangePoints([height, 0]);


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

svg.append("g")
.attr("class", "y axis")
.call(yAxis);
.axis text {
font: 10px sans-serif;
}

.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>

关于javascript - 如何在 D3.js 中解开 y 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32561590/

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