I've been trying to learn Javascript on my own for data visualization in the past couple days and is working/struggling with a grouped bar chart.

Chart working in progress: https://blockbuilder.org/lydiawawa/261aebe55bef8b556d257f3693cca37e

x-axis: Drug Categories

y-axis: Count of Drug Categories x S Categories

My current milestones:

  1. In the tooltip, I tried to index the respective x-axis mark to be defined as "Drug Category", but I'm stuck on indexing the right values because the array I'm dealing with is nested:

enter image description here

How do I point to the 'key' value (1,2,3,4,5,6) in the first level of nestedData so that it is defined as the drug category in the tooltip?

  1. How to sort the within-group counts in ascending order?

I think the code should be simlar to:

nestedData.sort(function(x, y){
   return d3.ascending(x.value, y.value);

How should I implement the sort with animation triggered by a radio button? Similar to this effect:


Appreciate for any help.

1 Answers

Gerardo Furtado On Best Solutions

Regarding the tooltip issue: the data for the outer array was bound to the groups that contain the rectangles.

Therefore, you can get it with this.parentNode:

const parentData = d3.select(this.parentNode).datum();

Regarding the sorting issue, you can sort the nested data with:

        return a.value - b.value

However, this won't make any difference: the order of the bars depend on the domain you passed to x1. So, unless you change the domain for each group (which is not a good practice in data visualisation), you can't sort the bars within groups.

Here is the updated blockbuilder: https://blockbuilder.org/GerardoFurtado/f4b4608bf07588f2b9291ac74c88f82c