javascriptangularjslinechartnvd3.js

How to add String values to nvd3 line chart x axis values?


I'm using nvd3 to create a bar chart in my angular js app. here is the script part

<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>

and here is the view 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>

How can I use strings like "aaa" "bbb" ... as x axis values. if I replace "2004" with a non numerical string it gives an error saying Error: Invalid value for attribute transform="translate(NaN,0)"


Solution

  • you can use chart xAxis format function as follows

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

    and then use your data as follows with label attribute.

    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"}]
    
                          }];
    

    Read this blogpost for more details.