D3.js折线图,时间在两个轴上

d3.js line chart with time on both axis

本文关键字:两个 折线图 js 时间 D3      更新时间:2023-09-26

我想画一个折线图,x轴是日期,y轴是时间,单位是分钟和秒。

轴都很好,但当我试图绘制线图时,它没有显示我预期的。

我最终得到了沿轴的线。

这是我的js代码

/**
 * Function for sorting times
 */
function numOrdA(a, b){ return (a[1]-b[1]); }
/**
 * Array of timestamps and times in seconds
 */
var data = [
    [1395237411, 130],
    [1395950916, 90],
    [1397557328, 95],
    [1398353666, 87]
];
/**
 * Sort the data by the time in seconds
 */
data.sort(numOrdA);
var width = 700,
    height = 400,
    padding = 100;
/**
 * Create an svg container
 */
var vis = d3.select("body").
    append("svg:svg")
    .attr("width", width)
    .attr("height", height);
/**
 * Create min and max dates for x axis
 */
var mindate = new Date,
    maxdate = new Date;
mindate.setTime(data[0][0] * 1000);
maxdate.setTime(data[data.length - 1][0] * 1000);
/**
 * Create min and max times for y axis
 */
var mintime = new Date,
    maxtime = new Date;
mintime.setTime(data[0][1] * 1000);
maxtime.setTime(data[data.length - 1][1] * 1000);
/**
 * Create y scale using min and max times
 */
var yScale = d3.time.scale()
    .domain([mintime, maxtime])
    .range([height - padding, padding]);
/**
 * Create x scale with min and max dates
 */
var xScale = d3.time.scale()
    .domain([mindate, maxdate])
    .range([padding, width - padding * 2]);
/**
 * Create the y axis with time in minutes and seconds
 */
var yAxis = d3.svg.axis()
    .orient("left")
    .scale(yScale)
    .tickFormat(d3.time.format("%M:%S"));
/**
 * Create the x axis with a date format
 */
var xAxis = d3.svg.axis()
    .orient("bottom")
    .scale(xScale)
    .tickFormat(d3.time.format("%a %x"));
/**
 * Append y axis
 */
vis.append("g")
    .attr("transform", "translate("+padding+",0)")
    .call(yAxis);
/**
 * Append the x axis
 */
vis.append("g")
    .attr("class", "xaxis")
    .attr("transform", "translate(0," + (height - padding) + ")")
    .call(xAxis);
/**
 * Rotate the text on the x axis
 */
vis.selectAll(".xaxis text")
    .attr("transform", function(d) {
        return "translate(" + this.getBBox().height*-2 + "," + this.getBBox().height + ")rotate(-45)";
    });
/**
 * Line function to plot the times (y axis) against dates (x axis)
 */
var line = d3.svg.line()
        .x(function(d) {
            return xScale(d[1]);
        })
        .y(function(d) {
            return yScale(d[0]);
        });
/**
 * Add the path to the svg
 */
vis.append("svg:path").attr("d", line(data));

下面是jsfiddle

上的当前代码

感谢您的帮助

其中一个主要问题是没有在line函数中将数据绘制为时间对象。

我找到了这个教程http://www.sitepoint.com/creating-simple-line-bar-charts-using-d3-js/,我遵循绘制折线图。

然后我想出了如何把所有东西都转换成基于时间的

我已经在Codepen上发布了最终代码。