如何将字符串值添加到nvd3折线图x轴值?

Cha*_*nna 3 javascript linechart angularjs nvd3.js

我正在使用nvd3在我的角度js应用程序中创建条形图.这是脚本部分

<script>
        var app = angular.module("nvd3TestApp", ['nvd3ChartDirectives']);

        function ExampleCtrl2($scope){
            $scope.exampleData2 = [
        {
            "key": "Series 1",
             "values": [ 
             ["2004",5],["2005",10],["2006",3],["2007",9],["2008",10],["2009",5]]
        }
    ];

    $scope.xFunction = function(){
    return function(d){
        return d[0];
    };
}

$scope.yFunction = function(){
    return function(d){
        return d[1];
    };
}

        }
    </script>
Run Code Online (Sandbox Code Playgroud)

这是视图div

<div ng-controller="ExampleCtrl2">
    <nvd3-line-chart
        data="exampleData2"
        id="xExample"
        width="550"
        height="300"
        showXAxis="true"
        showYAxis="true"
        x="xFunction()"
        y="yFunction()"
        tooltips="true">
            <svg></svg>
    </nvd3-line-chart>
</div>
Run Code Online (Sandbox Code Playgroud)

如何使用"aaa""bbb"等字符串作为x轴值.如果我用非数字字符串替换"2004",则会出现错误:错误:属性变换的值无效="translate(NaN,0)"

Cha*_*nna 13

您可以使用图表xAxis格式功能,如下所示

chart.xAxis
.axisLabel('Date')
.tickFormat(function(d) {
 var label = scope.totalLoanAmountData[0].values[d].label;
 return label;
});
Run Code Online (Sandbox Code Playgroud)

然后使用label属性将您的数据用于以下内容.

scope.totalLoanAmountData=[{
                        "key": "name of line one",
                        "values":[
                {x:1,y:2, label:"label1"},
                {x:1,y:2, label:"label2"},
                {x:1,y:2, label:"label3"},
                {x:1,y:2, label:"label4"},
                {x:1,y:5, label:"label5"},
                {x:1,y:2, label:"label6"},
                {x:1,y:7, label:"label7"},
                {x:1,y:2, label:"label8"},
                {x:1,y:8, label:"label9"}]

                           },

                      {"key": "name of line two",
                        "values": [

                {x:1,y:8, label:"label1"},
                {x:1,y:2, label:"label2"},
                {x:1,y:2, label:"label3"},
                {x:1,y:6, label:"label4"},
                {x:1,y:5, label:"label5"},
                {x:1,y:2, label:"label6"},
                {x:1,y:8, label:"label7"},
                {x:1,y:2, label:"label8"},
                {x:1,y:2, label:"label9"}]

                      }];
Run Code Online (Sandbox Code Playgroud)

阅读此博客文章了解更多详情.