To sort bars in an NVD3 bar chart, you can use the x or y axis tick values to control the order of the bars. By default, the bars are displayed in the order of the data provided. However, you can use a custom sorting function for the axis ticks to change the order of the bars.

Assuming you have an NVD3 bar chart like this:

<div id="chart"> <svg></svg> </div>

And your data is in the following format:

var data = [ { "key": "A", "value": 10 }, { "key": "B", "value": 20 }, { "key": "C", "value": 15 }, // Add more data points as needed ];

To sort the bars based on the value in ascending order, you can use the following JavaScript code:

nv.addGraph(function() { var chart = nv.models.discreteBarChart() .x(function(d) { return d.key; }) // Set the x-axis value to 'key' .y(function(d) { return d.value; }) // Set the y-axis value to 'value' .showValues(true) .duration(250); chart.xAxis .axisLabel('X Axis Label') .tickFormat(function(d) { return d; }) // Format the x-axis tick labels chart.yAxis .axisLabel('Y Axis Label') .tickFormat(d3.format('d')); // Format the y-axis tick labels as integers // Sort the data based on the 'value' in ascending order data.sort(function(a, b) { return a.value - b.value; });'#chart svg') .datum([{ key: 'Bar Chart', values: data }]) .call(chart); nv.utils.windowResize(chart.update); return chart; });

The data.sort() function is used to sort the data based on the value property in ascending order. This will change the order of the bars in the chart accordingly.

You can customize the sorting function to sort the bars in any order you desire. For example, to sort the bars in descending order, you can change the sort function as follows:

// Sort the data based on the 'value' in descending order data.sort(function(a, b) { return b.value - a.value; });

By adjusting the sorting function, you can control the order of the bars in your NVD3 bar chart as needed.

Have questions or queries?
Get in Touch