nvd3 stacked area chart looks glitchy how to fix?

后端 未结 1 813
再見小時候
再見小時候 2021-01-03 09:15

My stacked area chart looks like this:

\"enter

The data I used has the same nu

相关标签:
1条回答
  • 2021-01-03 10:01

    The NVD3 chart doesn't sort your data points into a left-to-right order along your x axis, so you're getting the strange criss-crossing shape.

    I assume there is some way to tell NVD3 to sort the data, but they have next to no documentation and I couldn't figure it out quickly. Instead, you can use this function to sort the data before you add it to the chart:

       data.forEach(function(d,i){ 
    
          d.values = d.values.sort(
              function(a,b){
                 return +a.t -b.t;
              }
          );
       });
    

    How this works:

    • data is the array of objects from the JSON file (you would use browserchartdata);

    • the Javascript Array.forEach(function(){}) method calls the passed-in function for each element of the array, and passes that function the element of the array and its index;

    • the Javascript Array.sort() method creates a sorted version of an array using the passed-in function to determine how two elements (a and b) compare;

    • the sort function I created uses the .t variable (which you're using for the x-axis) from each element in your array to determine whether a is bigger than b (and therefore should go after it in the sorted array);

    • I call this sort function on the values array of each data line, and then write-over the unsorted values array, so that the objects in data all end up with their values sorted from smallest to largest according to t.

    I tried it with your data on NVD3's "live code" site, and it looks fine.

    0 讨论(0)
提交回复
热议问题