Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8958099
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T15:08:26+00:00 2026-06-15T15:08:26+00:00

I am using d3 to make a stacked bar chart. Thanks to this previous

  • 0

I am using d3 to make a stacked bar chart.

Thanks to this previous question I am binding data associated with a parent node to a child node using parentNode.__ data__.key.

The data is an array with one object for each bar (e.g ‘likes’). Then each object contains an array of values which drive the individual rectangles per bar:

data =  [{
          key = 'likes', values = [
            {key = 'blue-frog', value = 1}, 
            {key = 'goodbye', value = 2}
          ]
        }, {
          key = 'dislikes, values = [
            {key = 'blue-frog', value = 3},
            {key = 'goodbye', value = 4}
          ]
        }]

The chart is working fine, and so is binding the parent metric data to a child svg attribute:

// Create canvas
bars = svg.append("g");

// Create individual bars, and append data
// 'likes' are bound to first bar, 'dislikes' to second
bar = bars.selectAll(".bar")
        .data(data)        
        .enter()
        .append("g");

// Create rectangles per bar, and append data
// 'blue-frog' is bound to first rectangle, etc.
rect = bar.selectAll("rect")
        .data(function(d) { return d.values;})
        .enter()
        .append("rect");

// Append parent node information (e.g. 'likes') to each rectangle    
// per the SO question referenced above        
rect.attr("metric", function(d, i, j) {
  return rect[j].parentNode.__data__.key;
});

This then allows the creation of tooltips per rectangle which say things like “likes: 2.” So far so good.

The problem is how to associate this same information with a click event, building on:

rect.on("click", function(d) {
  return _this.onChartClick(d);
});

// or

rect.on("click", this.onChartClick.bind(this));

It’s problematic because the onChartClick method needs access to the bound data (d) and the chart execution context (‘this’). If it didn’t I could just switch the execution context and call d3.select(this).attr("metric") within the onChartClick method.

Another idea I had was to pass the metric as an additional parameter but the trick of using function(d, i, j) here doesn’t seem to work because it isn’t run until a click event happens.

Can you suggest a solution?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T15:08:26+00:00Added an answer on June 15, 2026 at 3:08 pm

    You could use the closure to keep a reference to the parent data like this:

    bar.each(function(dbar) {            // dbar refers to the data bound to the bar
      d3.select(this).selectAll("rect")
          .on("click", function(drect) { // drect refers to the data bound to the rect
            console.log(dbar.key);       // dbar.key will be either 'likes' or 'dislikes'
          });
    });
    

    update:

    See below for various ways to access different levels in your DOM structure. Mix and match! See the live version of this and try to click on the .rect divs: http://bl.ocks.org/4235050

    var data =  [
        {
            key: 'likes',
            values: [{ key: 'blue-frog', value: 1 }, { key: 'goodbye', value: 2 }]
        }, 
        {
            key: 'dislikes',
            values: [{ key: 'blue-frog', value: 3 }, { key: 'goodbye', value: 4 }]
        }];
    
    var chartdivs = d3.select("body").selectAll("div.chart")
        .data([data]) // if you want to make multiple charts: .data([data1, data2, data3])
      .enter().append("div")
        .attr("class", "chart")
        .style("width", "500px")
        .style("height", "400px");
    
    chartdivs.call(chart); // chartdivs is a d3.selection of one or more chart divs. The function chart is responsible for creating the contents in those divs
    
    function chart(selection) { // selection is one or more chart divs
      selection.each(function(d,i) { // for each chartdiv do the following
        var chartdiv = d3.select(this);
        var bar = chartdiv.selectAll(".bar")
            .data(d)
          .enter().append("div")
            .attr("class", "bar")
            .style("width", "100px")
            .style("height", "100px")
            .style("background-color", "red");  
    
        var rect = bar.selectAll(".rect")
            .data(function(d) { return d.values; })
          .enter().append("div")
            .attr("class", "rect")
            .text(function(d) { return d.key; })
            .style("background-color", "steelblue");
    
        bar.each(function(dbar) {
          var bardiv = d3.select(this);
          bardiv.selectAll(".rect")
              .on("click", function(drect) { 
                d3.select(this).call(onclickfunc, bardiv);
              });
        });
    
        function onclickfunc(rect, bar) { // has access to chart, bar, and rect
          chartdiv.style("background-color", bar.datum().key === 'likes' ? "green" : "grey");
          console.log(rect.datum().key); // will print either 'blue-frog' or 'goodbye'
        }
      });
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I made a chart using Google Visualization's ColumnChart like this. It's basically a stacked
I'm trying to create a stacked bar chart with d3 from data in a
I have stumbled accross the following snippet, for creating horizontal bar chart using matplotlib:
I'm trying to make a 2-column 'table' using floated elements: <ul> <li class=odd>This will
I'm trying to create a stacked bar graph with errorbars* using ggplot2, similar to
I tried using make defconfig to compile the kernel, but as expected, it failed
I have built ICS source using make -j4, then I have modified the Music
I am trying to compile my piece of code using make. Normally I compile
I'm new to C programming. I want to compile C program using Make file.
2 questions: Does using MVC make it any easier to build 508/WAI compliant sites?

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.