Determining the percentage of a bar in d3.js when hovering over it

I am working with a d3 chart and looking to implement a tooltip feature that displays the label of the bar section along with the percentage it represents in relation to the total bar. Initially, I considered calculating the height of the hovered section to determine its percentage contribution to the whole bar. Here is my current approach within the mouseover event that logs data on hover:

d3.select(this).style("height")

While this method works as intended, I am struggling to find a way to retrieve the overall height of the entire bar (inclusive of all sections) to create my equation.

What would be the best way to proceed with this task? Alternatively, are there more efficient methods for obtaining the percentage value?

Answer №1

Each rectangle's data includes all the bars in its column within a data property:

https://i.stack.imgur.com/xzVGm.png

The data also contains the top and bottom values for the rectangle itself: d[0] and d[1].

We can calculate a percentage using this information:

.on("mouseover", function(d) { 
   var rectHeight = d[1] - d[0]; // Represents the top and bottom values of the rectangle.
   var columnHeight = d3.sum(d3.keys(d.data),function(k) {
      return +d.data[k]; // Sum of all bar heights in that column.
  });
  var percentHeight = rectHeight/columnHeight*100;

The units for rect height and column height mentioned above are not SVG units, but correspond to the dataset's units since we access the data directly without scaling.

d3.sum disregards NaN or undefined values, while the unary plus operator converts a string to a number, returning NaN if conversion is not possible. If you have a numerical x attribute, it needs to be excluded from the sum.

This results in the following snippet:

<!DOCTYPE html>
<meta charset="utf-8">
<svg id="chart" width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

var data = [
  {month: "January", toys: 16591, games: 1047, books: 0, crafts: 5757},
  {month: "February", toys: 42337, games: 129, books: 835, crafts: 0},
  {month: "March", toys: 3385, games: 1053, books: 6260, crafts: 10},
  {month: "April", toys: 353, games: 3724, books: 4038, crafts: 0}
];

var series = d3.stack()
    .keys(["toys", "games", "books", "crafts"])
    .offset(d3.stackOffsetDiverging)
    (data);

var svg = d3.select("svg"),
    margin = {top: 20, right: 30, bottom: 30, left: 60},
    width = +svg.attr("width"),
    height = +svg.attr("height");

var x = d3.scaleBand()
    .domain(data.map(function(d) { return d.month; }))
    .rangeRound([margin.left, width - margin.right])
    .padding(0.1);

var y = d3.scaleLinear()
    .domain([d3.min(series, stackMin), d3.max(series, stackMax)])
    .rangeRound([height - margin.bottom, margin.top]);

var z = d3.scaleOrdinal(d3.schemeCategory10);

var colors = ['#000','#000','#000','#000'];

svg.append("g")
  .selectAll("g")
  .data(series)
  .enter().append("g")
    .attr("fill", function(d) { return z(d.key); })
  .selectAll("rect")
  .data(function(d) { return d; })
  .enter().append("rect")
    .attr("width", x.bandwidth)
    .attr("x", function(d) { return x(d.data.month); })
    .attr("y", function(d) { return y(d[1]); })
    .attr("height", function(d) { return y(d[0]) - y(d[1]); })
    .on("mouseover", function(d){
        var rectHeight = d[1] - d[0];
        var columnHeight = d3.sum(d3.keys(d.data),function(k) {
           return +d.data[k];
        });
        console.log(Math.round(rectHeight/columnHeight*100)+"%");
    })

svg.append("g")
    .attr("transform", "translate(0," + y(0) + ")")
    .call(d3.axisBottom(x));

svg.append("g")
    .attr("transform", "translate(" + margin.left + ",0)")
    .call(d3.axisLeft(y));

function stackMin(serie) {
  return d3.min(serie, function(d) { return d[0]; });
}

function stackMax(serie) {
  return d3.max(serie, function(d) { return d[1]; });
}

</script>

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

When selecting an option triggers a pop-up in JavaScript

Implementing javascript and HTML. Consider this example: <select name='test' > <option value='1'> <option value='2'> <option value='3'> </select> If the user selects optio ...

Is it possible to iterate through div elements using .each while incorporating .append within an AJAX call?

After sending AJAX requests and receiving HTML with multiple div elements (.card), I am using .append to add new .card elements after each request, creating an infinite scroll effect. However, I am facing issues when trying to use .each to iterate over all ...

Managing two separate instances with swiper.js

Currently, I have set up two instances of swiper.js and I am looking to scroll both while interacting with just one of them. Update: My primary objective is to replicate the core functionality seen on the swiper homepage. Update 2: I came across this lin ...

Assign a JavaScript variable upon clicking a polygon on Mapbox

I have a MapBox map that consists of approximately 800 polygons representing census tracts, created using TileMill. The map has been integrated into an HTML page alongside a D3.js chart. A drop-down menu on the page allows users to select one of the 800 ce ...

Incorporating an unique identification code within the input field

I have a HTML code that displays geolocation information: <span id="currentLat"></span>, <span id="currentLon"></span> When combined with JavaScript, it works perfectly. However, I am trying to display the above value in a text fi ...

What is causing the click event handler to only function on the initial page?

Within my code for the "fnInitComplete" : function(oSettings, json), I am utilizing a selector like $('[id^=f_]').each(function (). The data for Datatables is retrieved server-side and "bProcessing":true I am aware that my selectors are only ef ...

The statement ... is not a valid function, it has returned undefined

Currently experimenting with AngularJS, encountered an error message: Argument 'Controller' is not a function, got undefined View the JSFiddle link, along with HTML code: <h2>Hata's Tree-Like Set</h2> <div ng-app ng-init="N=3 ...

Use Vue.js to display a class when the input is invalid and not empty

How can I apply a has-error class when an input is invalid and not empty in vue.js? <div class="form-group"> <input type="email" id="loginEmail" name="loginEmail" v-model="loginEmail" required> <label for="loginEmail">Email</label ...

Having issues with NextJs app router and redux-toolkit not resetting to initial state after server-side rendering (SSR)

I am facing a challenge in my NextJs project with the app router and redux/toolkit for state management. When navigating from one page to another, the data fetched on the previous page remains in the redux state even though it wasn't fetched on the cu ...

Calculate the product of a JavaScript variable and a PHP variable, then show the result on the

I need to calculate the product of a PHP variable value and a JavaScript variable, then show the result on the screen. Here is my PHP code: <?php require 'config.php'; session_start(); ?> <html> <head> < ...

Text transitions in a gentle fade effect, appearing and disappearing with each change

I want to create a smooth fade in and out effect for the text within a div when it changes or hides. After researching on Google and Stack Overflow, I found that most solutions involve adding a 'hide' CSS class and toggling it with a custom func ...

What is the best way to test the validity of a form while also verifying email availability?

I am currently working on implementing async validation in reactive forms. My goal is to disable the submit button whenever a new input is provided. However, I am facing an issue where if duplicate emails are entered, the form remains valid for a brief per ...

Is there an issue with the initial positioning of the tooltip in the seiyria angular-bootstrap slider?

After implementing the Seiyria angular-bootstrap-slider for a range slider, I encountered an issue where the tooltip is positioned incorrectly upon loading the page. While it functions correctly on a regular page, it appears in the wrong position within a ...

Having trouble displaying the output on my console using Node.js

Hey there, I'm new to this community and also new to the world of nodejs technology. I have encountered a problem that may seem minor to you but is quite big for me. Here's what's going on: In my code snippet, I want a user to input 3 value ...

Utilize the power of Wikitude within an Angular 2 application

I am currently working on integrating Wikitude Architect View in Angular 2 by referring to the code at this link. My goal is to implement this code in an Angular 2 compatible way. import * as app from 'application'; import * as platform from & ...

How do I automatically redirect to a different URL after verifying that the user has entered certain words using Javascript?

I want to create a function where if a user input on the "comments" id matches any word in my FilterWord's array, they will be redirected to one URL. If the input does not match, they will be redirected to another URL. The checking process should onl ...

AngularJS triggers the function on all controllers

I encountered a problem with a specific function in my code. The issue is that the scrollFunction continues to get triggered even when I navigate to another page. I would like to limit this functionality to only apply to a particular page within the cont ...

Guide on how to showcase JSON data using vanilla JavaScript within the Laravel framework

As a beginner in Laravel, I am looking to pass JSON data from my controller using vanilla JavaScript to my view blade. However, I am unsure of the steps to accomplish this. Below is an example of my controller: public function index(Request $request) { ...

Issues with the History API in AJAX Requests

Recently, I have come across a dynamically generated PHP code: <script> parent.document.title = 'Members | UrbanRanks'; $("#cwrocket_button").click(function(){ $("#module").load("modu ...

Is there a way to modify the Java class name to consist of two separate words?

(Edited) I am completely new to android app development. My question is: How can I rename a java class with two words instead of one? My main menu consists of 3 options, each linked to a java class: public class Menu extends ListActivity{ String cla ...