【问题标题】:Why is there no x or y axis shown on this d3 chart?为什么这个 d3 图表上没有显示 x 或 y 轴?
【发布时间】:2014-10-23 03:33:19
【问题描述】:

我有一个d3图表如下。

HTML:

<svg></svg>

JS:

var margin = {top: 10, right: 10, bottom: 10, left: 10},
width = 960,
height = 500;

var startOfWeek = moment().startOf("week").toDate();
var endOfWeek = moment().endOf("week").toDate();

var dxSyncEvents = [];
var now = moment();

var times = [];
var sites = [];

/*
Some stuff that pushes JS Date objects onto times[] and strings onto sites[]
*/

var xScale = d3.time.scale().domain([startOfWeek, endOfWeek]).range([0, 960]);
var yScale = d3.scale.ordinal().domain(sites).rangePoints(500, 10);

var xAxis = d3.svg.axis().scale(xScale).orient("bottom")
    .ticks(d3.time.hours, 12)
    .tickFormat(d3.time.format('%H:%M'))
    .tickSize(8)
    .tickPadding(8);
var yAxis = d3.svg.axis().scale(yScale).orient("left");

d3.select("svg")
    .attr("width", width)
    .attr("height", height)
    .selectAll("circle")
    .data(times)
    .enter().append("circle")
    .attr("r", "10px")
    .attr("fill", "black")
    .attr("cx", xScale)
    .attr("cy", yScale)
    .call(xAxis)
    .call(yAxis);

为什么图表上没有任何坐标轴?在屏幕上看不到它们,在开发者工具的 DOM 中也看不到它们。不过,我确实看到了一些圆圈。

有一些控制台错误并没有提供太多帮助:

Error: Invalid value for <path> attribute d="M-6,undefinedH0VundefinedH-6" 
Error: Invalid value for <g> attribute transform="translate(0,NaN)" (twice)

【问题讨论】:

  • 看起来您正在调用 .enter().append("circle") 调用的结果中的 xAxis 和 yAxis 对象,这将为次。我怀疑这不是你想要的。您可能希望为每个轴附加一个 g 元素并在这些轴上执行 .call(xAxis) 和 .call(yAxis) 。 bl.ocks.org/mbostock/3883245 是一个可能有帮助的简单折线图?
  • 本说了什么。此外,您似乎没有为范围点传递正确的数据结构。 github.com/mbostock/d3/wiki/Ordinal-Scales#ordinal_rangePoints
  • @BenLyall,请使用答案而不是评论,我会接受。谢谢。

标签: javascript d3.js


【解决方案1】:

您似乎在调用.enter().append("circle") 的结果调用xAxisyAxis 对象,这将为times 中的每个新数据元素创建一个circle 元素。

我怀疑这不是你想要的。您可能希望为每个轴附加一个 g 元素并在这些轴上执行 .call(xAxis).call(yAxis)

http://bl.ocks.org/mbostock/3883245 是一个简单的折线图,可能会有所帮助。

【讨论】:

    猜你喜欢
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 2020-07-01
    相关资源
    最近更新 更多