d3时间刻度-图形上的最后一个条形出现在图形外部 [英] d3 time scale - last bar on graph is appearing outside of the graph

查看:128
本文介绍了d3时间刻度-图形上的最后一个条形出现在图形外部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在D3版本4中建立一个条形图,使用时间刻度作为我的x轴.轴本身可以很好地渲染,但是条状图已关闭;图形中的最后一个条显示在轴范围的外面.如何指定适当的范围和/或x值?

I'm building a bar graph in D3 version 4, using a time scale as my x axis. The axis itself renders fine, but the bars are off; the last bar in the graph is appearing outside of the range of the axis. How do I specify the proper range and/or x values?

工作示例

代码段:

const xScale = (width, dates) =>
  scaleTime()
    .domain([new Date(dates[0]), new Date(last(dates))])
    .range([0, width])

svg.select('g')
  .selectAll(`.${styles['bar']}`)
  .data(series)
  .enter()
  .append('rect')
  .attr('class', styles['bar'])
  .attr('x', (d) => x(d.date))
  .attr('width', Math.floor(width / series.length))
  .attr('y', (d) => {
    const scaled = y(d.count)
      return height - scaled > 0 && height - scaled < 2
      ? height - 2
      : scaled
  })
  .attr('height', (d) => {
    const scaled = height - y(d.count)
    return scaled > 0 && scaled < 2
      ? 2
      : scaled
  })

推荐答案

问题不在于条的宽度,填充物或范围……问题不在于scaleTime的概念.例如,您的第一个值是(我指的是工作示例):

The problem is not the width of the bar, or the paddings, or the range... the problem is the very concept of scaleTime. For instance, your first value is (I'm referring to the working example):

Wed Sep 21 2016

哪个开始于 在2017年之前,但是由于条形的宽度,它会在2017年之后.您的最后一个值是(同样是工作示例):

Which starts before 2017 but, because of the width of the bars, goes after 2017. Your last value is (again, working example):

Sat Sep 21 2030

哪个位于域的末尾(2030)之前,但是由于条形图的宽度位于该比例尺的范围之后.

Which sits just before the end of the domain (2030) but, because the width of the bars, goes after the range for that scale.

您可以轻松地看到这是小提琴,我将域设置为2032年: https://jsfiddle.net/gerardofurtado/dnxc9cd9/

You can easily see this is this fiddle, where I set the domain going up to 2032: https://jsfiddle.net/gerardofurtado/dnxc9cd9/

一个简单的解决方案:如果您想要以x刻度显示年份的条形图,请解析获取该年份的日期并改用带刻度.

A simple solution: if you want a bar chart showing years in the x scale, parse your dates getting the years and use a band scale instead.

这篇关于d3时间刻度-图形上的最后一个条形出现在图形外部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆