gpt4 book ai didi

javascript - D3 : Adding second Y-axis, 限制 x 轴刻度为 2

转载 作者:行者123 更新时间:2023-11-29 23:38:07 24 4
gpt4 key购买 nike

使用 D3 v.3,我想消除 x 轴上除了两个刻度标签之外的所有刻度标签,并将第一个刻度标签直接放在 y 轴下方,将第二个刻度标签放在第二个 y 轴下方,如屏幕截图所示。我知道 .ticks(count) 函数不一定会为您提供您要求的刻度数。我怎样才能得到两个刻度并按照我的描述放置每个刻度?

这是我生成 x 轴的方式:

// Set the ranges
var xScale = d3.time.scale().range([0, width]);

// Define the axes
var xAxis = d3.svg.axis().scale(xScale)
.orient("bottom")
.ticks(2)
.tickFormat(formatTime);

(我不限于 v.3,但我不确定切换到 v.4 后我的现有代码会受到什么影响)。

enter image description here

最佳答案

使用 ticks 不是最好的方法,因为:

  1. “从量表的输入域返回大约计数代表值”(引用 API,强调我的)
  2. 您无法控制生成价格变动的位置

解决方案:

如果您将 xScale 域传递给 tickValues 函数,您将只有轴中的第一个和最后一个日期:

.tickValues(xScale.domain())

这是一个演示:

var svg = d3.select("svg");

var xScale = d3.time.scale().range([30, 470])
.domain([new Date(2016, 00, 01), new Date(2017, 11, 01)]);

var xAxis = d3.svg.axis().scale(xScale)
.orient("bottom")
.tickValues(xScale.domain())
.tickFormat(function(d) {
return d3.time.format("%b %Y")(d);
});

svg.append("g")
.attr("transform", "translate(0,50)")
.call(xAxis)
path,
line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<svg width="500" height="100"></svg>

关于javascript - D3 : Adding second Y-axis, 限制 x 轴刻度为 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45895993/

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