What is the best way to generate a hierarchical bar graph using d3.js?

I was attempting to modify Mike Bostock's Sortable Bar Chart by removing the transition property and sorting the bars based on their length, similar to how it is displayed in this example, without any interactivity.

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<style>

body {
  font: 10px sans-serif;
}

.bar rect {
  fill: steelblue;
}

.bar text {
  fill: white;
}

.axis path, .axis line {
  fill: none;
  stroke: black;
  shape-rendering: crispEdges;
}

</style>
<script src="http://mbostock.github.com/d3/d3.js"></script>
<script>

var margin = {top: 0, right: 10, bottom: 20, left: 10},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var index = d3.range(24),
    data = index.map(d3.random.normal(100, 10));

var x = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([0, width]);

var y = d3.scale.ordinal()
    .domain(index)
    .rangeRoundBands([0, height], .1);

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var bar = svg.selectAll(".bar")
    .data(data)
    .enter().append("g")
    .attr("class", "bar")
    .attr("transform", function(d, i) { return "translate(0," + y(i) + ")"; });

bar.append("rect")
    .attr("height", y.rangeBand())
    .attr("width", x);

bar.append("text")
    .attr("text-anchor", "end")
    .attr("x", function(d) { return x(d) - 6; })
    .attr("y", y.rangeBand() / 2)
    .attr("dy", ".35em")
    .text(function(d, i) { return i; });

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.svg.axis()
    .scale(x)
    .orient("bottom"));

var hierarchy = d3.layout.partition()
    .data(function(d) { return d.data; });

</script>

I tried replacing the code starting from `var sort = false;` with `var hierarchy =..`, but the modification didn't work as expected. Can someone provide guidance on how to achieve this?

Your assistance would be greatly appreciated. Thank you.

Answer №1

To organize the values in a specific order, make sure to include this line:

index.sort(function(x, y) { return data[y] - data[x]; });

For more details and examples, view the jsfiddle link: http://jsfiddle.net/7dbn5gt3/

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

Struggling to generate a Cylinder using three.js

I've been attempting to produce a Cylinder, but unfortunately without any luck. Here's the code I used: geometry02 = new THREE.CylinderGeometry( 20, 100, 100, 1000 ); material02 = new THREE.MeshBasicMaterial({color: 0x0000ff}); cylinder02 = new ...

Creating a personalized context menu in Javascript: The ultimate guide to incorporating copy and paste features

We are developing a unique context menu for our online text editor, complete with copy/paste options. However, we encountered difficulties accessing the system clipboard from within the browser. It once seemed impossible to achieve this, as discussed in th ...

Why aren't the kittens loading in Next Js?

Following the guidance in the Next Js documentation, I created a next.config.js file to inform Next Js that I want to incorporate kittens into my app. The resource for the kittens can be found at: This is how the next.config.js file appears: module.expor ...

Link scripts can sometimes cause issues with node.js

Greetings! I have successfully created a client-side SPA using vanilla-router. However, my Node.js server sometimes encounters an error when attempting to load a linked script. Uncaught SyntaxError: Unexpected token '<' This error only oc ...

Guide to activating "Snapping" feature using the "Select" function in Openlayers 3

I have created an application using OpenLayers 3 that allows users to draw lines or points on a map and add tags to them. While the existing functions in OL3 are helpful for drawing and modifying features, I found it challenging to select the items I drew ...

Working with AngularJS 1.0.7: The art of nesting promises within $http

I am currently trying to grasp the concept of promises in Angular 1.0.7, but I find both the syntax and the idea challenging. Previously, I posted a related question Nesting promises with $resources in AngularJS 1.0.7 which is functioning correctly. Howeve ...

Angular // binding innerHTML data

I'm having trouble setting up a dynamic table where one of the cells needs to contain a progress bar. I attempted using innerHTML for this, but it's not working as expected. Any suggestions on how to approach this? Here is a snippet from my dash ...

Having trouble passing variables via URL when using PHP and AJAX

I've encountered an issue while using AJAX to automatically update a web page every 5000 milliseconds. The problem arises when trying to retrieve data from the URL using $_GET or $_POST, as it only returns a value of 1. Below is an example code snippe ...

Is there a method in React Native to include the "share" icon in my drawer instead of a button?

How can I add a "share" icon to my drawer? I attempted to insert an icon using <Ionicons name="md-share" size={24} color="black" /> instead of a Button. However, when I do this, the icon is displayed without any title, unlike what I see in the sett ...

Combining Rxjs map and filter to extract countries and their corresponding states from a JSON dataset

I have a unique dataset in JSON format that includes information about countries and states. For example: { "countries": [ { "id": 1, "name": "United States" }, { "id": 2, "name": "India" }], "states": [ { ...

Retrieve information from every nested array and present it in sequential order

I need to extract the index of each element in a nested array structure. For example, I have an array with 5 subarrays, each containing multiple elements. My goal is to retrieve the first element from each subarray, then the second element, and so on. Her ...

Is it a graphics card malfunction or a coding complication? Delving into THREE.JS WebGL

Recently, I created a cool scene using three.js that was running perfectly until today. Strangely, without any changes to the code, I started encountering an error in every major browser - Chrome, Firefox, and Edge. The error message I am seeing is: THREE. ...

Can a Set (or Map) be held in a "frozen" state?

Despite the fact that Set is an Object, Object.freeze() specifically operates on the properties of the object, a feature not utilized by Map and Set: for example let m = new Map(); Object.freeze(m); m.set('key', 55); m.get('key'); // == ...

Troubleshooting: How to resolve the issue of receiving undefined values when passing API data to a child component with Axios in React

I am encountering difficulties in retrieving data that I pass to a child component. The issue may be related to the Promise not being resolved at the time of access, but I am unsure how to address it. My goal is to ensure that the data is fully retrieved f ...

Exploring the Origin of "props" in ReactJS

Currently, I am diving into the world of the official reactJS tutorial and you can find it here: https://reactjs.org/tutorial/tutorial.html#passing-data-through-props My journey with reactJS has been interesting so far, although there are still some parts ...

What is the best way to define a function in React hooks - using a function statement or

When working with a react hook and needing to define a function inside it, which approach is preferable? useEffect(() => { //... function handler() {} //... }, []); or should I use the newer const declaration instead? useEffect(() => { ...

Utilizing Radio buttons for validation in react-hook-form

After creating a form with radio buttons and implementing validation using React Hook Form, I encountered an issue where the console always displayed "on" regardless of the selected radio button. <div className=""> <label ...

Incorporate a variable into a string

My task here is to prepend a variable before each specific string in the given text. For example: var exampleString = "blabla:test abcde 123test:123"; var formattedString = "el.blabla:test abcde el.123test:123"; In this case, whenever there is a pattern ...

Obtain the jQuery dialog's closure event within the $.Ajax completion function

I have developed a custom jQuery plugin that utilizes jQuery Dialog to showcase messages. Specifically, I am using it within my jQuery $.ajax -->done function. My goal is to capture the close event of the Dialog in the .ajax function so that I can redir ...

Guide on incorporating data from one component to another within Angular 4

I have been struggling to include one component's HTML data into another component. Despite several attempts, I have not been successful in achieving the desired outcome. </hello> </hello> serves as the selector tag for the HelloComponent ...