nvd3 stacked area chart looks glitchy how to fix?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-01 00:59:33

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!