如何将“ Y”比例数据与“ X”比例域匹配

时间:2019-01-17 18:09:02

标签: d3.js

我已成功在X轴上显示了开始/结束域(最近36小时)的变更单,并希望在我的Y轴上显示符合要求的变更单编号。我知道这是需要更新的行,经过多次不同的迭代后,我感到很困惑:

ySc.domain(yScDomArr).padding(.1);

当前显示三个条,我只希望在Y轴上显示三个对应的更改顺序。这是我的代码和小提琴:https://jsfiddle.net/dtepdc/5pkx42yf/

const dataset = [
{
    start_date: "2019-01-16T08:30:40",
    end_date: "2019-01-16T09:32:25",
    elapsed_date: 130,
    coNum:"CO19044"
},
{
    start_date: "2019-01-15T04:30:40",
    end_date: "2019-01-15T05:32:25",
    elapsed_date: 189,
    coNum:"CO12904"
   },
   {
    start_date: "2019-01-15T22:05:40",
    end_date: "2019-01-15T22:32:25",
    elapsed_time: 89,
    coNum:"CO18345"
    },
    {
    start_date: "2019-01-12T22:00:40",
    end_date: "2019-01-12T22:40:25",
    elapsed_time: 89,
    coNum:"CO12005"
    }
];



const coNumW = window.innerWidth,
    coNumH = window.innerHeight,
    margin = {top: coNumH * 0.15, right: coNumW * 0.05, bottom: coNumH * 0.12, left: coNumW * 0.12},
    w = coNumW - margin.left - margin.right,
    h = coNumH - margin.top - margin.bottom;


const xSc = d3.scaleTime().range([0, w]),
      ySc = d3.scaleBand().range([h, 0])
      xAxis = d3.axisBottom(xSc),
      yAxis = d3.axisLeft(ySc),
      yScDomArr = [],
      dateFormat = d3.timeFormat("%Y-%m-%d %I:%M %p");

const svg = d3.select("body")
    .append("svg")
    .attr("width", coNumW)
    .attr("height", coNumH)
    .append("g").classed("no-select", true)
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

dataset.forEach(function(d, i) {
    yScDomArr.push(d.coNum);
    d.start_date = new Date(d.start_date);
    d.end_date = new Date(d.end_date);
});

const start = moment().format('LLL');
const end = moment().subtract(60, 'hours').format('LLL');

xSc.domain([new Date(start), new Date(end)])
.range([0, w]);
ySc.domain(yScDomArr).padding(.1);

svg.append("g")
        .attr("class", "x Axis")
        .attr("transform", "translate(0, " + h + ")")
        .call(xAxis)

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

 const tasks = svg.append("g").attr("class", "dataCont")
        .selectAll("g")
        .data(dataset)
        .enter()
        .append("g")
        .on("mouseenter", showData);

 tasks.append("rect")
        .attr("x", function(d) {
            return xSc(d.start_date ) + 2;  // + 2 is for padding
        })
        .attr("y", function(d) {
        return ySc(d.coNum);
        })
        .attr("width", function(d) {
            return xSc(d.start_date) - xSc(d.end_date) - 2;
        })
        .attr("height", function(d) {
             return ySc.bandwidth();
        })
        .attr("fill", "green");

function showData(d) {
    const dur = (d.end_date - d.start_date)/3600000;
    console.log("-" + d.coNum + "- start_date: " + dateFormat(d.start_date) + " || end_date: " + dateFormat(d.end_date) + " || duration: " + dur + " hours" )
}

0 个答案:

没有答案