2

我试图弄清楚如何制作以小时为单位的可缩放 y 轴。我希望 y 轴的范围从早上 7 点到下午 5 点。我的 x 轴以天为单位。

目前,我的 y 轴以小时为单位,但它仅在 y 轴顶部显示 12AM。我不确定从早上 7 点到下午 5 点该去哪里。我的代码确实在两个轴上都进行了缩放。

任何帮助,将不胜感激 :)

// Define the min and max date 
var mindate = new Date(2013,0,20),  // TODO: clip date 
    maxdate = new Date(2013,0,25);

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

var x = d3.time.scale()
    .domain([mindate, maxdate])
    .range([0, width]);

var y = d3.time.scale()
    .domain([mindate, maxdate])
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(d3.time.days, 1)
    .tickFormat(d3.time.format("%A : %d")); // d is for testing 

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(d3.time.days, 12)
    .tickFormat(d3.time.format("%I %p")); // For 12 hour time 

var zoom = d3.behavior.zoom()
    // .x(x)
    .y(y)
   .scaleExtent([1, 10])
    .on("zoom", zoomed);

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 + ")")
    .call(zoom);

svg.append("rect")
   .attr("width", width)
   .attr("height", height);

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

svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

function zoomed() {
     svg.select(".x.axis").call(xAxis);
     svg.select(".y.axis").call(yAxis);
4

2 回答 2

2

我不是 100% 确定这是否是您所追求的,但我已将您的问题解释为如何在同一天以 1 小时的步长创建从早上 7 点到下午 5 点的比例。首先是为所需时间的 y 比例创建一组日期,如下所示:

var ymindate = new Date(2013,0,20, 7),  // TODO: clip date 
    ymaxdate = new Date(2013,0,20, 17);

下一步只需对您的代码进行少量更改。刻度设置为 d3.time.hours 而不是天,步长设置为 1 小时,如下所示。

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(d3.time.hours, 1)
    .tickFormat(d3.time.format("%I %p"));

如果您只想在多天出现上午 7 点和下午 5 点,则必须创建一组自定义刻度并使用时间间隔

于 2013-10-22T20:37:24.673 回答
0

您需要相应地设置 y 比例的域。目前,您的最小和最大日期都是全天,因此您只能获得一个时间值。例如,如果您使用

var mindate = new Date(2013,0,20, 7, 0, 0, 0),
    maxdate = new Date(2013,0,25, 17, 0, 0, 0);

你应该在 y 轴上得到你想要的时间。

于 2013-10-22T20:20:59.803 回答