x = 0处的轴标签未显示

时间:2018-02-27 12:45:11

标签: d3.js

我使用D3绘制折线图。 x = 0时的值不会显示。

enter image description here

轴的代码如下所示。

const xScale = d3
    .scaleTime()
    .domain(d3.extent(data[0].series, d => d.time))
    .range([xPadding, width - xPadding]);

const xAxis = d3
    .axisBottom(xScale)
    .ticks(4)
    .tickSizeOuter(0)
    .tickSizeInner(0)
    .tickFormat(d3.timeFormat('%Y'));

我不确定为什么它没有显示x = 0的标签,即2014.在检查SVG时,只显示三个刻度线,但x = 0的那个不在SVG元素中。

CodePen:https://codepen.io/vijayst/pen/bLJYoK?editors=1111

1 个答案:

答案 0 :(得分:1)

我看到了不同的解决方案,各有利弊。第三种解决方案应该是最干净,最通用的。

手动添加左勾号:

由于d3自己处理x轴刻度的位置,所以这样做的一种方法是(如果数据集是固定的)将手动添加缺失的刻度:

svg 
  .append("g")
  .append("text")
  .text("2014-02-01") // can be retrieved from data instead of being harcoded
  .style("font-size", 10)
  .style("font-family", "sans-serif")
  .attr("transform", "translate(0," + (height - yPadding + 10) + ")")

看起来很棒,但在这种情况下,如果对于给定的数据集,d3选择显示靠近轴左边缘的刻度线,则可能会出现问题。 d3的标记和我们所包含的标签都可以重叠。

将x-scale修改为在一年的第一天之前开始:

另一种解决方案是增加左侧的x轴范围,使其在第一个点的日期前一个月开始。要尝试这一点,我们可以替换:

.domain(d3.extent(data[0].series, d => d.time))

.domain(d3.extent([new Date(2013, 12), new Date(2019, 1)]))

允许d3合法地包含" year-tick" 2014年,在x轴的开头。

但在这种情况下,第一个点将具有x轴范围开始的偏移量。

将特定刻度推到d3自动生成的刻度:

另一种解决方案:我们可以将特定的刻度推到d3自动生成的刻度线上。但这需要将刻度的格式修改为"%Y-%m"。

为此,请替换:

.tickFormat(d3.timeFormat("%Y"));

.tickFormat(d3.timeFormat("%Y-%m"));

然后我们可以将新的特定刻度推送到由d3生成的刻度集:

var ticks = xScale.ticks();
ticks.push(new Date(2014, 1, 1));
xAxis.tickValues(ticks);

并在图表的左侧和右侧包含一些填充,因为现在刻度标签的一部分显示在图表外:

const svg = d3
  .select("#chart")
  .append("svg")
  .attr("width", width)
  .attr("height", height)
  .style("padding-left", 15)
  .style("padding-right", 15);
相关问题