javascript - d3.js 时间刻度轴刻度不等间距
问题描述
我已经使用d3.js-v3
time scale绘制了我的 x 轴d3.time.scale()
。
我的轴刻度不是等距的。
我怎样才能有等距的刻度?
这是我的代码
var customTimeFormat = d3.time.format("%d %b");
var margin = {
top: 0,
right: 20,
bottom: 20,
left: 20
},
width = 550 - margin.left - margin.right,
height = 20 - margin.top - margin.bottom;
var x = d3.time.scale()
.domain([new Date("08/21/2019"), new Date("09/5/2019")])
.range([0, width]);
var xAxis = d3.svg.axis()
.scale(x)
.tickFormat(customTimeFormat);
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")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
.axis text {
font: 10px sans-serif;
}
.axis line,
.axis path {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
解决方案
您可以通过将其添加到轴定义中以 2 天的间隔获取刻度
.ticks(d3.timeDay.filter(d => d3.timeDay.count(0, d) % 2 === 0))
请参阅 d3 v5.7.0 的代码片段
var customTimeFormat = d3.timeFormat("%d %b");
var margin = {
top: 0,
right: 20,
bottom: 20,
left: 20
},
width = 550 - margin.left - margin.right,
height = 20 - margin.top - margin.bottom;
var x = d3
.scaleTime()
.domain([new Date("08/20/2019"), new Date("09/7/2019")])
.range([0, width]);
var xAxis = d3
.axisBottom()
.scale(x)
.ticks(d3.timeDay.filter(d => d3.timeDay.count(0, d) % 2 === 0))
.tickFormat(customTimeFormat);
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")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<html>
<body>
</body>
</html>
推荐阅读
- angular - Angular 7,从日期输入中减去日历天数
- java - 有没有办法随机化哪个 if 语句在 Java 中运行第一、第二、第三、第四等等?
- jquery - Laravel Echo - 未捕获的类型错误:无法读取未定义的属性“通道”
- git - 如何统一分支之间的文件权限差异?
- mysql - MariaDB / Columnstore 引擎内存被阻塞
- javascript - 在正则表达式前缀中使用变量?
- vb.net - 如何在 vb 中清理 StackFrame 类的对象。网??
- database - 使用 AngularFireList 时出错,数据检索
- php - 可以将冒号与提取语句一起使用吗?
- python - 尝试编写 Python 代码来计算字符串中不同元音的数量?