javascript - D3 中未显示的所有月份

标签 javascript d3.js

代码:

var margin = {top: 30, right: 40, bottom: 30, left: 50},
    width = 600 - margin.left - margin.right,
    height = 270 - margin.top - margin.bottom;

var parseDate = d3.time.format("%b").parse;
var formatTime = d3.time.format("%B");

var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height,0]);

var xAxis = d3.svg.axis().scale(x)
    .orient("bottom").ticks(5);

var yAxis = d3.svg.axis().scale(y)
    .orient("left").ticks(5);

var valueline = d3.svg.line()
    .x(function(d) { return x(d.month); })
    .y(function(d) { return y(d.shop2); });

var valueline2 = d3.svg.line()
    .x(function(d) { return x(d.month); })
    .y(function(d) { return y(d.shop1); });

var div = d3.select("body").append("div")   
    .attr("class", "tooltip")               
    .style("opacity", 0);

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 + ")");

// Get the data
d3.csv("data.csv", function(error, data) {
    data.forEach(function(d) {
        d.month = parseDate(d.month);
        d.shop1 = +d.shop1;
        d.shop2 = +d.shop2;
    });

    // Scale the range of the data
    x.domain(d3.extent(data, function(d) { return d.month; }));
    y.domain([0, d3.max(data, function(d) { return (d.shop1, d.shop2); })]);


});

</script>
</body>

数据集:data.csv

month,shop1,shop2
Jan,100,98
Feb,103,99
Mar,110,110
Apr,112,111
May,102,99
Jun,99,98
Jul,100,97
Aug,101,99
Sep,102,97

输出: enter image description here

我是 javaScript 和 D3 的新手,想知道我的代码可能有什么问题。我在最终图中得到的是 1900 而不是“Jan”,但所有其他月份都显示正确。非常感谢任何对此的帮助。

最佳答案

代替这个

var xAxis = d3.svg.axis().scale(x)
    .orient("bottom").ticks(5);

这样做是为了给出 x 轴刻度的格式

var xAxis = d3.svg.axis().scale(x).ticks(5)
.orient("bottom").tickFormat(d3.time.format("%b"));

关于javascript - D3 中未显示的所有月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37086458/

相关文章:

javascript - 使用对象来简化 d3.js 中的代码

Javascript/Node.js ] 使用 await 处理 promise 的错误

javascript - 检查表单是否提交成功html5

javascript - 将当前时间转换为最接近的半小时

javascript - 尝试使用 d3.max 返回最大日期

javascript - d3.js 更新视觉

javascript - 我的 AJAX 脚本没有给出任何输出

javascript - 如何使文本框只接受 0-10 之间的数字,并且只接受小数部分的 0.5?

php - 人力车 : data for multiple series not working

javascript - 在 D3.js hover 中过滤和匹配 json 数据