Navigating through an array with multiple dimensions and varying lengths using d3

I am working with a multidimensional array of integer values to create a dynamic bar graph using d3.js. The challenge lies in the fact that each row can have a variable number of values. My goal is to generate color-coded rectangles for each row based on the value of the elements, with the height of each rectangle depending on both the number of values in a row and the average value of that row.

You can visualize how the bar graph should look like by visiting this link: https://i.sstatic.net/gYZAe.png

In the provided image, each column represents the values in a row within the multidimensional array. However, my current struggle lies in iterating over the multidimensional array when executing the following code:

bar = svg.selectAll(".bar")
.data(allrankings)
.enter().append("rect")

Please note that 'allrankings' refers to the multidimensional array.

Currently, I am resorting to creating a separate large array containing all rankings in one dimension and iterating through it while keeping track of which row each element belongs to. I am wondering if there might be a more efficient approach to resolving this issue?

Answer №1

To access multidimensional data, utilize svg groups and make multiple .data calls. For more information, refer to Mike Bostock's tutorial on nested selections available at:

In the scenario where allrankings is structured as a multidimensional array like [[0,1,2,3],[2,3]], one way to manipulate the data could be:

// Transform the data to display average and number of elements for each bar
var data = allrankings.map(function(rankings){
    var avg;
    avg = rankings.reduce(function(a,b){ return a+b; })/rankings.length;
    return rankings.map(function(d){
        return {val: d, avg: avg, numBars: rankings.length};
    });
});

var barGroups = svg.selectAll(".bar-groups")
  .data(data)
  .enter()
  .append("g")
  .attr("transform", function(d, i){
     return "translate("+ i*20 + ",0)"; // Scales can be used for precision
   })
  .classed("bar-groups",true);

var bars = barGroups
  .selectAll(".bars")
  .data(function(d){ 
    return d; // Returns a one-dimensional array of objects
   })
  .enter()
  .append("rect");

Subsequently, you can assign values using the .avg, .val, and .numBars properties (e.g.

bars.attr("height", function(d){ return d.avg/d.numBars; });

An example similar to this approach utilized in stacked bar charts was described by Gilsha. It can be viewed at: https://bl.ocks.org/mbostock/3886208

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery, eliminate a single value from all drop down options

I am facing an issue where I have multiple drop-downs with the same values. When a user selects "Lunch" from one of the drop-downs, I need to remove "Lunch" from the rest. Below is my code: Frontend code: <?php for($i=1; $i<=7; $i++) {?> <se ...

The AngularJS $resource is taking the entire object and embedding it into the URL

I am currently utilizing Angular version 1.4.8 along with Angular UI and TypeScript in my project. The models are defined as follows: export interface IBatch extends ng.resource.IResource<IBatch> { id: Number; ... } export interface IBatchR ...

Choose2 - Dynamic search with auto-complete - keep track of previous searches

Currently, I am utilizing Select2 version 3.5.1 and have successfully implemented remote data loading with the plugin. However, I have a query regarding enhancing the search functionality. Below is a step-by-step explanation of what I aim to achieve: Cre ...

React with TypeScript: The children prop of this JSX tag is specifically looking for a single child of type ReactNode, but it seems that multiple children were passed instead

For my class project in APIs, I am using react-typescript but running into issues. My problem arises when attempting to loop through an array of "popular" movies using .map. However, I keep getting this error message: "This JSX tag's 'children&ap ...

Issue with formik onchange event not filling data in Material UI TEXTFIELD component

Greetings! I am currently working on a React project where I am managing the authentication process. I am using Material UI and Formik for validation and handling input changes. However, I encountered an issue with my onchange Formik handler in the TEXTF ...

Transforming raw data into an object in Angular: A step-by-step guide

Does anyone have tips on converting this raw data from a websocket message into an object for use in an Angular and Ionic project? var data = message.payload; console.log(data); After logging 'data' to the console, here is the result: ...

Tips for managing static resources using webpack on the server side?

I am currently working on developing a universal React app that utilizes webpack for both server and client-side operations. One issue I am facing involves importing images into the project. I would like to achieve the following: import someImage from &ap ...

Can you explain the distinction between these two methods of slicing in a numpy array?

My numpy array looks like this: X=array([[0, 44.0, 72000.0], [2, 27.0, 48000.0], [1, 30.0, 54000.0], [2, 38.0, 61000.0], [1, 40.0, 63777.0], [0, 35.0, 58000.0], [2, 38.0, 52000.0], [0, 48.0, 79000.0], [1, 50.0, 83000.0], [0, 37. ...

Sort a 2D integer array using the qsort function in C

Do you have a question? I've been attempting to sort a 2D integer array using the qsort function in C, but I keep encountering a segmentation fault. When I compile the code with the following command: gcc -g -lm -Werror -Wfatal-errors -Wall -Wext ...

The state variable is not accurately captured as it passes through various components

For the sake of readability, I have omitted certain sections of my original code. Apologies if this leads to any confusion! In App.js, there is a state variable defined as follows: const [tasks, setTasks] = useState([]) From App.js, the state varia ...

disable hover effect

Kindly visit the link below and click on 'Story': Upon mouseover, the animation can be observed: How can I remove this effect? The CSS I am using for this is as follows: .storypageThumb1 { float:left; width:175px; height:91px; ...

Struggling with passing a function along with parameters to a component in React has been a challenge for me

Currently utilizing React in conjunction with NextJS My goal is to send a function, along with its parameters, to my 'Alerts' component so that it can wait for user input before executing the function. For instance, prior to clearing a list, I ...

When the update button is clicked, the textfield is hidden; it reappears upon refreshing the page

Our marketplace multi-vendor site on Magento allows sellers to list their products for sale. The frontend displays the price using the following code: Phtml <input onFocus="showPriceCancel('<?php echo $products->getId(); ?>');" clas ...

Error encountered in Angular JS: $parse:syntax Syntax Error detected

var app=angular.module('myapp',[]) app.controller('myctrl',Myfunction); function Myfunction($scope,$compile){ var self=this; $scope.text=s4(); $scope.adding=function(){ var divElement = angular.element($("#exampleId")); ...

Animating objects in three.js along the projection plane

I am looking to implement a feature where objects can be moved along a plane parallel to the projection plane using the mouse. The challenge is to keep the distance between any selected object and the camera's projection plane constant throughout the ...

Customize Vuetify Menu by adding a unique custom keypad component for editing text fields

I am currently developing an app using vuetify, and I am encountering some challenges with the v-menu feature. The issue arises when I click on a text input field, it triggers the opening of a v-menu. Within this menu, there is a custom component that I h ...

Troubleshoot: Why is my Google Chrome not playing videos? Uncover the solution with a

I have created a webpage with an HTML video tag that loads dynamically from a JSON file. I am currently using Chrome 50 for this project. The response is successful, and when inspecting the page using Chrome's developer tools, I can see the video tag ...

Customize the width of a DataTable cell in VuetifyJS

I am currently utilizing the VuetifyJS Data Table and I'm looking for a way to reduce the spacing between the entries in each header cell. Adding a width to each header did not achieve the desired result, as it seems there is a minimum predefined widt ...

Generate the entity and then transfer the data into an array

I am dealing with multi-level hierarchies that need to be displayed in a select list. Once the user selects values from the table column, they should be able to filter by clicking on the column. var name = ['Akansha', 'Navya']; var age ...

Find the matching value of the first element in an array by comparing it with values in another array using

Imagine having two different arrays const arr1 = [5, 3, 2, 7, 4]; const arr2 = [10, 9, 8, 12, 6, 5, 7]; The goal is to find and return the first matching value without resorting to using dual for loops. We need a solution that doesn't involve itera ...