d3.js 项目_渲染问题

Dmi*_*try 8 javascript visualization d3.js github-pages

我有一个基于 lib构建的项目v.7.6.1

它托管在 GitHub Pages 上,在我的笔记本电脑上运行完全正常: 在此输入图像描述

但在大多数其他设备上渲染不正确: 在此输入图像描述

y控制台中的和属性错误cy在此输入图像描述


我在这里复制了代码。这可能有什么问题吗?

async function drawLineChart() {
  const pathToCsv = 'https://raw.githubusercontent.com/dsibi/portfolio/main/projects/line-graph-2/data/time_entries.csv';
  let rawDataset = await d3.dsv(";", pathToCsv);

  const record = {
    date: '',
    duration: ''
  };

  let dataset = [];

  for (let i = 0; i < rawDataset.length; i++) {
    let currRecord = Object.create(record);
    const [day, month, year] = rawDataset[i]['Start date'].split('.');
    currRecord.date = new Date(+year, +month - 1, +day);
    const [hours, minutes, seconds] = rawDataset[i]['Duration'].split(':');
    currRecord.duration = new Date(+year, +month - 1, +day, +hours, +minutes, +seconds);
    dataset.push(currRecord);
  }

  dataset.forEach(function(element) {
    let timeString = element.duration.toLocaleTimeString();
    let timeEl = timeString.split(':');
    element.durationSeconds = (+timeEl[0]) * 60 * 60 + (+timeEl[1]) * 60 + (+timeEl[2]);
  });

  var groupedDataset = [];
  dataset.reduce(function(res, value) {
    if (!res[value.date]) {
      res[value.date] = {
        date: value.date,
        totalDurationSeconds: 0
      };
      groupedDataset.push(res[value.date])
    }
    res[value.date].totalDurationSeconds += value.durationSeconds;
    return res;
  }, {});

  const xAccessor = d => d.date;
  const formatHours = d3.format(".2f");
  const yAccessor = d => +formatHours(d['totalDurationSeconds'] / 3600);
  const yAccessorLine = d => d['meanDurationHours'];
  let datasetWeeks = downsampleData(groupedDataset, xAccessor, yAccessor);
  const vacation = [{
    name: 'vacation',
    start: new Date('2022-06-16'),
    end: new Date('2022-06-26'),
  }, ];

  let dimensions = {
    width: window.innerWidth * 0.8,
    height: 400,
    margin: {
      top: 15,
      right: 40,
      bottom: 40,
      left: 40,
    },
  }
  dimensions.boundedWidth = dimensions.width - dimensions.margin.left - dimensions.margin.right
  dimensions.boundedHeight = dimensions.height - dimensions.margin.top - dimensions.margin.bottom

  // 3. Draw Canvas
  const wrapper = d3.select("#wrapper")
    .append("svg")
    .attr("width", dimensions.width)
    .attr("height", dimensions.height);

  const bounds = wrapper.append("g")
    .style("transform", `translate(${dimensions.margin.left}px, ${dimensions.margin.top}px)`);

  // 4. Scales
  const xScale = d3.scaleTime()
    .domain(d3.extent(groupedDataset, xAccessor))
    .range([0, dimensions.boundedWidth]);

  const yScale = d3.scaleLinear()
    .domain(d3.extent(groupedDataset, yAccessor))
    .range([dimensions.boundedHeight, 0])
    .nice();

  const meanHours = d3.mean(groupedDataset, yAccessor);

  bounds.append('line').attr('class', 'mean');

  const meanLine = bounds.select('.mean')
    .attr('x1', 0)
    .attr('x2', dimensions.boundedWidth)
    .attr('y1', yScale(meanHours))
    .attr('y2', yScale(meanHours));


  const xAxisGenerator = d3.axisBottom()
    .scale(xScale);

  const xAxis = bounds.append("g")
    .attr("class", "x-axis")
    .style("transform", `translateY(${dimensions.boundedHeight}px)`)
    .call(xAxisGenerator);

  // 5. Draw Data
  //dots
  const dots = bounds.selectAll(".dot")
    .data(groupedDataset)
    .enter()
    .append("circle")
    .attr("cx", d => xScale(xAccessor(d)))
    .attr("cy", d => yScale(yAccessor(d)))
    .attr("r", 2)
    .attr("class", "dot");

  //line
  const lineGenerator = d3.line()
    .x(function(d) {
      // console.log(xScale(xAccessor(d)))
      return xScale(xAccessor(d))
    })
    .y(d => yScale(yAccessorLine(d)))
    .curve(d3.curveCatmullRom.alpha(.5));
  // .curve(d3.curveMonotoneX);

  const line = bounds.append("path")
    .attr("class", "line")
    .attr("d", lineGenerator(datasetWeeks))

  // 6. Draw Peripherals
  const yAxisGenerator = d3.axisLeft()
    .scale(yScale)
    .ticks(7);

  const yAxis = bounds.append("g")
    .attr("class", "y-axis")
    .call(yAxisGenerator);

};

drawLineChart();

function downsampleData(data, xAccessor, yAccessor) {
  const weeks = d3.timeWeeks(xAccessor(data[0]), xAccessor(data[data.length - 1]))

  return weeks.map((week, index) => {
    const weekEnd = weeks[index + 1] || new Date()
    const days = data.filter(d => xAccessor(d) > week && xAccessor(d) <= weekEnd)
    const meanTotalDurationHours = d3.mean(days, yAccessor)
    const meanDurationHours = meanTotalDurationHours === undefined ? 0 : d3.mean(days, yAccessor)
    return {
      date: week,
      meanDurationHours: meanDurationHours
    }
  })
};
Run Code Online (Sandbox Code Playgroud)
.line {
  fill: none;
  stroke: #eb4511;
  stroke-width: 3;
}

.mean {
  stroke: #7d82b8;
  stroke-dasharray: 2px 4px;
}

.y-axis-label {
  fill: black;
  font-size: 1.4em;
  text-anchor: middle;
}

.x-axis-label {
  fill: black;
  font-size: 1.4em;
  text-anchor: middle;
}

.dot {
  fill: #9c9b98;
}

.mean_text,
.vacation_text {
  fill: #7d82b8;
  font-size: .8em;
  font-weight: 800;
  text-anchor: start;
}

.x-axis line,
.y-axis line,
.domain {
  stroke: gray;
}

.tick text,
.y-axis-label {
  fill: gray
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.6.1/d3.min.js"></script>
<html lang="en">

<body>
  <div id="wrapper">
  </div>

</body>

</html>
Run Code Online (Sandbox Code Playgroud)

0st*_*ne0 2

您的问题是由 引起的toLocaleTimeString()

\n
\n

console.log()当在以下部分添加 a 时:

\n
dataset.forEach(function(element) {\n    let timeString = element.duration.toLocaleTimeString();\n    let timeEl = timeString.split(\':\');\n    console.log(timeString, timeEl)\n    element.durationSeconds = (+timeEl[0]) * 60 * 60 + (+timeEl[1]) * 60 + (+timeEl[2]);\n});\n
Run Code Online (Sandbox Code Playgroud)\n

桌面显示:

\n
00:19:34 (3)\xc2\xa0[\'00\', \'19\', \'34\']\n
Run Code Online (Sandbox Code Playgroud)\n

但我的手机(使用 chrome 远程检查器)显示:

\n
12:06:53 AM (3)\xc2\xa0[\'12\', \'06\', \'53 AM\']\n
Run Code Online (Sandbox Code Playgroud)\n

所以当你这样做的时候,* 60 + (+timeEl[2])你就会得到NaN应得的53 AM

\n
\n

您应该更改时间逻辑,使其能够解析 24 小时和 12 小时格式时间,例如,使用:

\n\n
\n

这是我解决这个问题的尝试。

\n

我曾经new Date()将其转换为日期对象。然后使用valueOf() 来获取unix时间戳。现在我们只需要把它们相减就可以得到durationSeconds

\n
dataset.forEach(function(element) {\n    let secondsDiff = new Date(element.duration).valueOf() - new Date(element.date).valueOf();\n    element.durationSeconds = secondsDiff;\n});\n
Run Code Online (Sandbox Code Playgroud)\n

这在我的笔记本电脑和移动设备上都有效:

\n

更新的片段:

\n

\r\n
\r\n
dataset.forEach(function(element) {\n    let timeString = element.duration.toLocaleTimeString();\n    let timeEl = timeString.split(\':\');\n    console.log(timeString, timeEl)\n    element.durationSeconds = (+timeEl[0]) * 60 * 60 + (+timeEl[1]) * 60 + (+timeEl[2]);\n});\n
Run Code Online (Sandbox Code Playgroud)\r\n
00:19:34 (3)\xc2\xa0[\'00\', \'19\', \'34\']\n
Run Code Online (Sandbox Code Playgroud)\r\n
12:06:53 AM (3)\xc2\xa0[\'12\', \'06\', \'53 AM\']\n
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n