Arranging Data in Horizontal Bar Chart with D3.js

I have a dataset that includes the following frequency data:

FrequencyData = [
              {label:"QWERTY", value:0},
              {label:"AZERTY", value:14},
              {label:"AAAAAA", value:20},
              {label:"BBBBBB", value:30},
              {label:"CCCCCC", value:40},
              {label:"DDDDDDD", value:45},
              {label:"EEEEEE", value:21},
          ];

Here is the code I am using to create a horizontal bar chart based on this dataset:

function createBarChart(dataset) {

              $elem[0].svg = null;

              var margin = {top: 20, right: 10, bottom: 120, left: 10},
                  width = $elem[0].parentNode.clientWidth - margin.left - margin.right,
                  height = $elem[0].parentNode.clientHeight - margin.top - margin.bottom;

              var mappedDataset = dataset.map(function(d) { return d.value; });

              var div = d3.select($elem[0]).append("div").attr("class", "toolTip");
              var formatPercent = d3.format("");

              var y = d3.scale.ordinal()
                //.domain(mappedDataset.sort(function(a, b) { return mappedDataset[a] - mappedDataset[b]; }))
                .domain(dataset.map(function(d) { return d.label; }))
                .rangeRoundBands([0, height], 0.1, 0.3);
              var x = d3.scale.linear()
                .domain([0, d3.max(dataset, function(d) { return d.value; })])
                .range([0, width]);

              var xAxis = d3.svg.axis()
                      .scale(x)
                      .tickSize(-height)
                      .orient("bottom");

              d3.select($elem[0]).selectAll("svg").remove()

              var svg = d3.select($elem[0]).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 + ")");

              svg.append("g")
                      .attr("class", "x axis")
                      .attr("transform", "translate(0," + height + ")")
                      .call(xAxis);

              svg.append("g")
                      .attr("class", "x axis")
                      .attr("transform", "translate(0," + height + ")")
                      .call(xAxis);

              svg.select(".y.axis").remove();
              svg.select(".x.axis").remove();

              svg.append("g")
                      .append("text")
                      .attr("transform", "rotate(0)")
                      .attr("x", 170)
                      .attr("dx", ".1em")
                      .style("text-anchor", "end")
                      .text("Frequency of Visit/Time Spent (mins)");
                      //console.log(dataset);

              var bar = svg.selectAll(".bar")
                        .data(dataset, function(d) { return d.label; })

              // new data:
              bar.enter().append("rect")
                      .attr("class", "bar")
                      .attr("x", function(d) { return 0; })
                      .attr("y", function(d) { return y(d.label); })
                      .attr("width", function(d) { return x(d.value); }) // return 0 if want to animate
                      .attr("height", y.rangeBand())
                      .text(function(d) { return d.label; });

              svg.selectAll(".bartext")
                      .data(dataset, function(d) { return d.label; })
                      .enter()
                      .append("text")
                      .attr("class", "bartext")
                      .attr("text-anchor", "middle")
                      .attr("fill", "white")
                      .attr("x", function(d,i) {
                          if (d.value==0) {return x(d.value)+50;}
                          return x(d.value)/2;
                      })
                      .attr("y", function(d,i) {
                          //if (d.value==0){return};
                          return y(d.label)+15;
                      })
                      .text(function(d){
                        //if (d.value==0){return};
                           return d.label;
                      });


              bar.on("mousemove", function(d){
                      if ( in_transition ) { return; }
                      div.style("left", d3.event.pageX+"px");
                      div.style("top", d3.event.pageY-130+"px");
                      div.style("display", "inline-block");
                      div.html((d.value)+"%");
                  });
              bar.on("mouseout", function(d){
                      if ( in_transition ) { return; }
                      div.style("display", "none");
                  });

              // removed data:
              bar.exit().remove();



              $elem[0].svg = svg;

            }, delay);

          }

Currently, the bars are not sorted in descending order as I intend. I have tried sorting the Y-axis using the labels, but this does not produce the desired result. I have also attempted to use D3 sorting functions without success:

mappedDataset.sort(function(a, b) { return mappedDataset[a] - mappedDataset[b]; }))

If you have any ideas on how to correctly sort the bars in descending order, I would greatly appreciate the assistance. Thank you.

Answer №1

Check out this solution:

console.log(info);
info = info.sort(function(x, y) {
    return x.amount - y.amount;
}).reverse();
console.log(info);

Visit this jsFiddle for a demonstration:

https://jsfiddle.net/9tzp4d6c/

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

The error message indicates that the property 'current' is not found in the type '[boolean, Dispatch<SetStateAction<boolean>>]'

During my React/Typescript project, I encountered an issue involving cursor animations. While researching the topic, I stumbled upon a CodePen (Animated Cursor React Component) that functioned perfectly. However, when attempting to convert it into a Types ...

React 18 introduces a new feature, ReactDOMClient.createRoot(), which allows for hot module replacement with Webpack. This allows developers to update components in real time without

After upgrading React to version 18, I encountered a console error with my Webpack dev server when the hot module replacement triggers and injects new JavaScript code: Warning: You are calling ReactDOMClient.createRoot() on a container that has already be ...

Arrange the JSON data retrieved from an HTTP request using a function before storing it in Firestore

I am in need of a function that can efficiently handle information received from an HTTPS request and categorize the data into specific collections or documents depending on its content. For instance, if I receive a JSON object with the data "Color: blue, ...

What criteria should I use to determine if a post has been favorited by a user using Mongoose?

Creating a function for users to like posts has been my recent project. Each post is stored as an object in my MongoDB collection with a specific schema. { title: String, text: String } On the other hand, users have their own unique schema as well. ...

What is the correct way to route requests to /api/ressource in a production environment?

In my development environment, I have set up a webpack dev configuration where my front-end server runs on port 8080 and my backend server runs on port 3000. Here is how I configured my webpack dev server: proxy: { '/api': 'http://localh ...

Needing to utilize the provide() function individually for every service in RC4

In Beta, my bootstrapping code was running smoothly as shown below: bootstrap(App, [ provide(Http, { useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, helperService: HelperService, authProvider: AuthProvider) => new CustomHt ...

Easily modify and manage state on-the-fly using TextFields

Is the title conveying my intentions clearly? If not, please let me know. Essentially, I am looking to create a component that generates a form based on a JSON file. For example, if someone clicks on "light" in the navbar, I want the form to display fields ...

Creating a form that can identify both letters and numbers using JavaScript

Is it possible to create an <input> field that can recognize both letters and numbers while disregarding spaces and capitalization? Here is my current progress, aiming for the feedback to display as "right" when 9 H 6 U 8 f is entered in the field, ...

Tips for improving the efficiency of the find_average_number(array) simple function?

I successfully completed a CodeWars challenge where I wrote the function find_average to calculate the average of numbers in an array. However, I now have some questions: 1) How can I optimize this code in terms of Big-O notation? Is there a way to reduce ...

What is the correct way to upload an image using the Express static middleware?

Just diving into express, I have this setup in my server: app.use(express.static(path.join(__dirname, 'includes'))); When it comes to my client-side JavaScript, I'm simply using the URL like so: var img = $("<img />").attr('s ...

Tips for limiting the maximum number of characters in CkEditor 5 for react js

Is there a way to limit the amount of characters in a CKEditor textarea in a React JS environment? I'm trying to set a maximum character count for the text area in CKEditor Does anyone have any examples or suggestions on how to achieve this? retur ...

Unable to successfully append a unique character using jQuery

I need help with displaying special characters, specifically the degree symbol (°), in JavaScript/jQuery. Despite my efforts, it is not showing up correctly on the webpage. How can I fix this issue and ensure that the degree sign appears as desired? I ...

Ways to collect email address or name from an email message

Suppose I send an email to someone with a link at the bottom. The text of the link might be something like click me. When the user clicks on this link, they will be directed to a webpage. On this webpage, a message saying "Thank you" will be displayed a ...

Display a text box upon clicking an item

I've been curious about how to create the effect of a text box or div that appears when clicked on, similar to what you see in this. Scroll down and click on "show patchnotes"; I've been puzzled by this for a while but haven't come across a ...

Innovative way to design a menu using HTML, CSS, and JavaScript that dynamically resizes to a specific width

I'm currently working on a website and I'm trying to create a menu with specific width of 700px. However, I'm unsure whether to tackle this using CSS, JavaScript, or a combination of both. Which approach would be the most straightforward for ...

A guide on understanding tab-formatted text in a textarea using JavaScript (Vuejs)

Trying to decipher a text that has been copied into a Word table, the formatting is very confusing. I am looking to extract the rows as objects in an array, with the columns serving as properties of each object. I would like to accomplish this using Vuejs ...

JavaScript now assigns a value of null in place of undefined

When working with JavaScript, it's important to understand that undefined can be reassigned. Because of this, it is recommended to create a self-executing function to ensure that undefined remains undefined. Are there any other values that are loosely ...

Typescript's tree-pruning strategy design for optimization

I've been working on developing a library that enforces the use of specific strategies for each target. The current structure I have in place is as follows: [Application] -> contains -> [player] -> contains -> [renderer] In the current s ...

The selected value is not displayed in the Material UI select component

My select component is showing the menu items and allowing me to select them, but it's not displaying the selected value. However, its handle function is functioning correctly because when I choose an item, the value in the database gets updated. Bel ...

Build a custom Angular2 pipe to convert JSON data into an array through iteration

I am attempting to take the JSON data provided below and convert it into an array for use with *ngFor='let item of items', which will allow me to display data as item.name, etc... This is what I have tried: var out = []; for(var key1 in object) ...