【问题标题】:nvd3 repeating months on x-axisnvd3 在 x 轴上重复月份
【发布时间】:2016-11-16 12:50:36
【问题描述】:

我正在尝试创建一个折线图来显示一年中的数据,并且我使用 Nvd3 制作了一个简单的图表,但是我在 x 轴上显示月份时遇到了困难,我查看了其他帖子,但是出于某种原因,它只显示“Jan”12 次。

这是我的代码

        var chart;
        var data;

        nv.addGraph(function () {
            chart = nv.models.lineChart()
                .options({
                    duration: 300,
                    useInteractiveGuideline: true
                });

            // chart sub-models (ie. xAxis, yAxis, etc) when accessed directly, return themselves, not the parent chart, so need to chain separately
            chart.xAxis
                .axisLabel("Month")
                .tickFormat(function(d) { return d3.time.format('%b')(new Date(d)); });

            chart.yAxis
                .axisLabel('Tenants')
                .tickFormat(function (d) {
                    if (d == null) {
                        return 'N/A';
                    }
                    return d3.format(',.2f')(d);
                });

            //DATA
            data = getData();

            d3.select('#chart1').append('svg')
                .datum(data)
                .call(chart);

            nv.utils.windowResize(chart.update);

            return chart;
        });


        //GETTING DATA    
        function getData() {
            var finance = [];

            for (var i = 1; i <= 12; i++) {
                finance.push({
                    x: i,
                    y: i
                })
            }
            return [
                {
                    values: finance,
                    key: "Finance",
                    color: "#2ca02c"
                }
            ];
        }

JS 小提琴:https://jsfiddle.net/0q10cyte/

//编辑 重复几个月

【问题讨论】:

    标签: javascript d3.js nvd3.js


    【解决方案1】:

    现在,您的x 只是一个数字:

    finance.push({
        x: i,
        y: i
    })
    

    一个可能的解决方案(在许多解决方案中)是将其转换为实际日期:

    finance.push({
        x: new Date().setMonth(i),
        y: i
    })
    

    这是更新后的小提琴:https://jsfiddle.net/2futpb98/

    【讨论】:

    • 谢谢,它确实有效,但是有重复的几个月,这是一个错误吗?
    • 我没有看到任何重复的月份。
    • 我已经包含了一个屏幕截图,似乎只有当视图足够大时才会显示
    • 这不是一个重复的月份。这是时间刻度的正常行为,特别是因为您设置了d3.time.format('%b')。这就是时间尺度的工作原理。你有 16 个刻度,你希望刻度显示什么?
    • 感谢您告诉我,有没有办法可以在不显示两次的情况下完成?
    猜你喜欢
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多