Using d3.js to toggle visibility of bars when clicking on the legend

          // Handling the browser onresize event
          window.onresize = function () {
              scope.$apply();
          };


          scope.render = function (data) {
              
              var ageNames = d3.keys(data[0]).filter(function (key) {
                  return key !== "GateName" &&
                         key !== "QualityGateOrCheck" &&
                         key !== "GateId" &&
                         key !== "PercentOfCompletedByAllGates" &&
                         key !== "PercentOfCompletedByActiveGates" &&
                         key !== "PercentOfActiveByAllGates" &&
                         key !== "PercentageOfCompleteByAllGates" &&
                         key !== "PercentageOfCompleteByActiveGates" &&
                         key !== "PercentageOfActiveByAllGates" &&
                         key !== "PercentageOfCompleteByAllChecks" &&
                         key !== "PercentageOfCompleteByActiveChecks" &&
                         key !== "PercentageOfActiveByAllChecks";
              });


              data.forEach(function (d) {
                  d.ages = ageNames.map(function (name) { return { name: name, value: +d[name] }; });
              });

              var margin = { top: 20, right: 20, bottom: 30, left: 60 }, width = 1140 - margin.left - margin.right, height = 300 - margin.top - margin.bottom;
              var ticks = [0, 25, 50, 75, 100];
              var x0 = d3.scale.ordinal().rangeRoundBands([0, width - 160], .1);
              var x1 = d3.scale.ordinal();
              var y = d3.scale.linear().range([height, 0]);
              var color = d3.scale.ordinal().range(["#3366cc", "#830300", "#97be0d"]);
              var xAxis = d3.svg.axis().scale(x0).orient("bottom");
              var yAxis = d3.svg.axis().scale(y).orient("left").tickValues(ticks);
              var svg = d3.select("#barChart").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 + ")");

              x0.domain(data.map(function (d) { console.log(d.GateName); return d.GateName; }));
              x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]);
              y.domain([0, d3.max(data, function (d) { return d3.max(d.ages, function (d) { return d.value; }); })]);
              svg.append("g").attr("class", "x axis").attr("transform", "translate(0," + height + ")").call(xAxis);
              svg.append("g").attr("class", "y axis").call(yAxis).append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy", ".71em").style("text-anchor", "end").text("% Percentage");
              var state = svg.selectAll(".state").data(data).enter().append("g").attr("class", "g").attr("transform", function (d) { return "translate(" + x0(d.GateName) + ",0)"; });
              state.selectAll("rect").data(function (d) { return d.ages; }).enter().append("rect")
                                                     .attr("width", x1.rangeBand())
                                                     .attr("x", function (d) { return x1(d.name); })
                                                     .attr("y", function (d) { return y(d.value); })
                                                     .attr("height", function (d) { return height - y(d.value); })
                                                     .style("fill", function (d) { return color(d.name); })
                                                     .each(function (d) { this._current = d; }) 
                                                     .on("mouseover", function (d) {
                                                        
                                                         var xPosition = parseFloat(d3.select("rect").attr("x")) + x1.rangeBand() / 2;
                                                         var yPosition = parseFloat(d3.select("rect").attr("y")) / 2 + height / 2;

                                                         
                                                         d3.select("#tooltip")
                                                             .style("left", xPosition + "px")
                                                             .style("top", yPosition + "px")
                                                             .select("#toolipHeading, #value")
                                                             .text(d.name, d.value);

                                                         
                                                         d3.select("#tooltip").classed("hidden", false);

                                                     }).on("mouseout", function () {

                                                         //Hide the tooltip
                                                         d3.select("#tooltip").classed("hidden", true);

                                                     });

              state.selectAll("rect").data((function (d) { return d.ages; }))
                                     .attr("id", function (d) { return d.name; })
                                     .append("title");


              var KPILegend = ["PercentageOfComplete/AllRequirements", "PercentageOfComplete/ActiveRequirements", "PercentageOfActive/AllRequirements"];

              var legend = svg.selectAll(".legend")
                              .data(KPILegend.slice().reverse())
                              .enter().append("g")
                              .attr("class", "legend")
                              .attr("transform", function (d, i) { return "translate(0," + i * 20 + ")"; });

              legend.append("rect").attr("x", 900)
                                   .attr("width", 15)
                                   .attr("height", 15)
                                   .style("fill", color)
                                   .style('stroke', color)
                                   .on('click', function (label) {
                                       

                                       var svg1 = d3.select("#barChart");

                                       svg1.selectAll('.g').selectAll('rect#PercentageOfCompleteByAllRequirements').style("display", 'block');
                                   });


          };

          
          scope.$watch('data', function (chartDataNew, chartDataOld, attributes) {
              

              if (chartDataNew != undefined && chartDataOld == undefined) {
                  if (scope.data != undefined) {

                      $("#barChart").empty();
                      scope.render(scope.data);
                  }
              }
              else if (chartDataNew != undefined && chartDataOld != undefined) {
                  
                  var NewChartJSON = JSON.stringify(chartDataNew);
                  NewChartJSON = JSON.parse(NewChartJSON);

                  $.each(NewChartJSON, function (i, val) {
                      delete NewChartJSON[i].ages;
                  });

                  var OldChartJSON = JSON.stringify(chartDataOld);
                  OldChartJSON = JSON.parse(OldChartJSON);
                  NewChart = NewChartJSON;

                  var flag = false;

                  $.each(NewChart, function (index, dataNew) {
                      $.each(OldChartJSON, function (index, dataOld) {
                          if (dataNew.GateId == dataOld.GateId) {
                              if (dataNew.GateName != dataOld.GateName ||
                                  dataNew.QualityGateOrCheck != dataOld.QualityGateOrCheck ||
                                  dataNew.PercentageOfCompleteByAllRequirements != dataOld.PercentageOfCompleteByAllRequirements ||
                                  dataNew.PercentageOfCompleteByActiveRequirements != dataOld.PercentageOfCompleteByActiveRequirements ||
                                  dataNew.PercentageOfActiveByAllRequirements != dataOld.PercentageOfActiveByAllRequirements) {
                                  flag = true;
                              }
                          }
                      });
                  });

                  if (flag == true) {

                      $("#barChart").empty();
                      scope.render(scope.data);
                  }
              }
          }, true);


      }
  };

This is a custom implementation of a grouped bar chart using d3.js. There are 3 items in the legends section. Clicking on a legend bar with the id "xyz" should toggle its visibility.

To achieve this functionality, the following code snippet can be used:

svg1.selectAll('.g').selectAll('rect#PercentageOfCompleteByAllRequirements').style("display", 'block');

The above code selects all bars with the specified ID and attempts to change their display property. However, there might be issues with the expected behavior not being achieved despite applying the style property successfully.

If you are facing any challenges with this implementation, please seek assistance from the community or support resources.

https://i.sstatic.net/LYGoE.png

Answer №1

Upon initial inspection, it appears that you have chosen .g as the class of 'g'. I assume you meant to simply use g, since there are no classes of type g in this code?

If that solution doesn't solve the issue, please inform me. I am unsure which element(s) you intend to apply a block style to, clarifying this would assist me in providing further assistance.

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

Passing a variable in an AngularJS $http.get() call to retrieve a specific section of a JSON data file

Currently, I am using json files to stub my $http.get() calls. I am trying to retrieve a specific subset of the json file in my angular controller. Despite looking at other solutions that recommend setting a params property in the Get call, it does not see ...

The NestJs project fails to display the updates when using the "tsc" command before running either "npm run start" or "npm run start:dev"

As a beginner in nestjs, I decided to start a tutorial to learn more about it. However, whenever I make updates or changes to my code, I don't see any changes reflected in the results. Can someone please assist me with this issue? Below are my tsconfi ...

Every time a user clicks on the map, Leaflet automatically adjusts the center

Currently, I am utilizing leaflet within Vue.js to display an image. I have incorporated custom features such as draggable boxes on the map that can be transformed into rectangle leaflet objects by leaflet. My objective is to be able to click on a rectang ...

Issues with the Node Package Manager's watch command functionality

Having installed the frontend dependency in my Vue.js project, I attempted to run the command npm run watch. I updated the scripts section in package.json as shown below- "scripts": { "dev": "npm run development", &qu ...

Is there a way to create a self-contained installation package for my Vue application?

Is it possible for my application to be downloaded and installed without requiring internet access after the download is complete? I am looking to create a standalone installer for this purpose. Are there any suggestions on how to go about implementing t ...

Arrange a collection of objects based on various nested properties

I am faced with the challenge of managing an array of objects representing different tasks, each categorized by primary and secondary categories. let tasks = [ { id: 1, name: 'Cleanup desk', primary_category: { id: 1, na ...

Plot data points from geojson onto a leaflet map using markers

How can I efficiently import geoJson data (containing over 2000 coordinates) into a leaflet map? Below is a brief snippet of geo json: { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { ...

Is there a way to determine if a string is empty, even if it contains hard returns?

I am currently working on a function that checks if a string is empty or not, but it seems to be missing the detection of new lines. export const isStrEmpty = function(text: string): boolean { return !text || text.match(/^ *$/) !== null; }; I attempted ...

What is the best way to implement JavaScript for loading and removing content based on button clicks on a webpage?

I'm in need of a vanilla JavaScript solution (I know JQuery options exist, but I want to stick to vanilla JS for now)? Currently, I am using a simple page as a testing ground for my ongoing project. The page consists of two buttons that load HTML pag ...

"Refreshing UI-View with AngularJS and UI-Router: A Guide on Reloading Your

I am struggling with Angular UI-Router as I am encountering an issue where the state is not being reloaded. Here is a snippet of my code: app.config(function ($urlRouterProvider, $stateProvider) { $urlRouterProvider.otherwise("/home"); $stateProvi ...

Can someone explain the crazy math used in three.js?

I've recently started learning three.js, and I keep encountering these complex mathematical formulas that seem confusing. Take this example for instance: mouse.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeig ...

Dynamic value changes in AngularJS checkboxes controlled by ng-model within controller

I have a page that loads data from a database and displays it in a grid. It has a button to manually refresh the data, as well as a checkbox for automatic refreshing. Below is the HTML code: <div id="TestViewTable" ng-controller="testTableManager" ng- ...

Failure to choose a value in AngularJS using the Chosen directive

I am currently developing a project with AngularJS and I need to display the selected value. To achieve this, I am utilizing the chosen filter available at: https://github.com/leocaseiro/angular-chosen Below is the code snippet that I have implemented: ...

Retrieve URL query parameters using AngularUI

I am currently working with the AngularUI library and I am trying to retrieve the query parameters from a URL (for example: #\books\:categoryID?publisher=xyz or #\books\value?publisher=xyz). When using $stateParams, the data is extract ...

The code is functioning properly, however it is returning the following error: Anticipated either

Can you explain why this code is resulting in an unused expression error? <input style={{margin:'25px 50px 0',textAlign:'center'}} type='text' placeholder='add ToDo' onKeyPress={e =>{(e.key ==='En ...

Simple Method to Retrieve one document from Firebase v9 in a React Application

Is it possible to retrieve a document from Firebasev9 using a slug instead of an id with the useDocument Hook? useDocument Hook import { useEffect, useState } from "react" // firebase import import { doc, onSnapshot } from "firebase/firesto ...

Stop the removal of the CSS content property

When a user enters and re-enters their password, I have a form that checks the strength of the password and displays text accordingly. However, I noticed that if a user makes a mistake and uses the backspace to re-enter the password, the text from data-tex ...

"The event triggers the function with an incorrect parameter, leading to the execution of the function with

Currently, I am working with a map and a corresponding table. The table displays various communities, each of which has a polygon displayed on the map. My goal is to have the polygons highlighted on the map when hovering over a specific element in the tabl ...

The download of package-lock.json is not initiated for a linked GitHub URL

I currently have two projects on GitHub. One is named "mylibrary" and the other is "test-project." In my "test-project," I have linked "mylibrary" using its GitHub URL in the package.json file as shown below. dependencies: { "mylibrary": "git+ssh://& ...

Is it possible to dynamically incorporate directives within an AngularJS application?

I'm attempting to utilize several custom directives within the Ionic framework. The dynamic structure is like <mydir-{{type}}, where {{type}} will be determined by services and scope variables, with possible values such as radio, checkbox, select, ...