Unable to zoom in on D3 Group Bar Chart

I've designed a group bar chart and attempted to implement zoom functionality. However, I noticed that the zoom only works for the first group of bars and not for the entire chart. Any assistance on this matter would be highly appreciated. Thank you in advance.

You can view a working example here:

http://jsfiddle.net/fiddlefollower/qkHK6/893/

Here are the details of the code:

var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var x1 = d3.scale.ordinal();
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c",  "#ff8c00"]);
var xAxis = d3.svg.axis().scale(x0).orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".1s"));

 var svg = d3.select("#chart").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 + ")")
.call(d3.behavior.zoom().scaleExtent([1, 10]).on("zoom", zoom));

 var ageNames = d3.keys(data[0]).filter(function(key) { return key !== "State"; });
 console.log("ageNames="+JSON.stringify(ageNames));
data.forEach(function(d) {
d.ages = ageNames.map(function(name) { return {name: name, value: +d[name]}; });
console.log("d.ages="+JSON.stringify(d.ages));
});

x0.domain(data.map(function(d) { return d.State; }));
x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data, function(d) { 
console.log(" before retuen d.ages="+d.ages);
return d3.max(d.ages, function(d) 
{ console.log("d.value;="+d.value);
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", ".5em")
.style("text-anchor", "end")
.text("Population");

 var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "state")
.attr("transform", function(d) { return "translate(" + x0(d.State) +    ",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); });

function zoom() {
svg.select(".state").attr("transform", "translate("+ d3.event.translate[0]+")scale(" + d3.event.scale + ",1)");
svg.select(".x.axis").attr("transform", "translate(" + d3.event.translate[0]+","+(height)+")").call(xAxis.scale(x0.rangeRoundBands([0,width*d3.event.scale],.5*d3.event.scale)));
svg.select(".y.axis").call(yAxis);
}

Answer №1

The zoom function in this context allows for selecting all groups of bars when using svg.selectAll(".state") instead of just the first group with svg.select(".state").

By grouping all states within a "g" element and assigning it to the variable allStates:

var allStates = svg.append("g")
  .attr("class", "allStates");

We can now reference this new variable when creating the state groups:

var state = allStates.selectAll(".state")
  .data(data)
  .enter().append("g")
  .attr("class", "state")
  .attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; });

This new variable is also utilized in the zoom function:

svg.select(".allStates").attr("transform", "translate(" + d3.event.translate[0]+",0)scale(" + d3.event.scale + ",1)");

When a doubleclick event occurs, the zoom will be applied to all states simultaneously.

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

ways to conceal icon image when the textbox is devoid of content

Is there a way to hide the clear icon from a text box if the length inside the text box is less than 1? I attempted the following code, but it didn't work for me. The inner icon is not hidden when the input field length is less than 1. For a demo ex ...

Cracking the code of the @ symbol within this particular context

https://github.com/react-dnd/react-dnd/blob/master/examples/04%20Sortable/Simple/Card.js I'm trying to comprehend the significance of the @ symbol in this example. This is meant to be a straightforward drag and drop demonstration, but the implementa ...

What is the proper way to implement parameters and dependency injection within a service?

My objective is to achieve the following: (function(){angular.module('app').factory("loadDataForStep",ls); ls.$inject = ['$scope','stepIndex'] function ls ($scope, stepIndex) { if ($routeParams ...

Triggering of NVD3 Angular Directive callback occurring prematurely

Lately, I've delved into utilizing NVD3's impressive angular directives for crafting D3 charts. They certainly have a sleek design. However, I'm encountering numerous challenges with callbacks. While callbacks function smoothly when incorpor ...

Issue with adding object to array using forEach() function

As I navigate my way through an express route, I am puzzled as to why the "purchasedCards" array turns out empty after going through these database calls. Despite successfully gathering all the necessary information from various DB Queries and placing it i ...

Guide on submitting a form via Ajax on a mobile app

Looking for a way to submit the form located in components/com_users/views/login/tmpl/default_login.php using Ajax. <form action="<?php echo JRoute::_('index.php?option=com_users&task=user.login'); ?>" method="post"> <fie ...

Rendering v-html in VueJS requires a delayed binding value that can only be triggered by clicking inside and outside of a textarea control

I'm currently experiencing an issue with a textarea that is bound to a v-model with a specific value. The problem arises when the content of the textarea is changed via JavaScript - the displayed value, represented by {{{value}}}, doesn't update ...

Unable to get spacing correct on loading page

My attempt at creating a loading page using CSS and HTML has hit a roadblock. I'm trying to show a loading bar that ranges from 0% to 100%. Despite my use of justify-content: space-between, I can't seem to get it right. I've searched through ...

Overcoming Troublesome Login Input Box in Web

In an effort to streamline tasks in our office, I am working on automating certain processes. Specifically, this program is designed to log into our insurance company's website and extract information for payroll purposes. Below is the code snippet th ...

Tips for concealing overlay when the cursor hovers

Can anyone help me with a code issue I'm having? I want to hide an overlay after mouse hover, but currently it remains active until I remove the mouse from the image. Here is the code: .upper {position: absolute; top: 50%; bottom: 0; left: 50%; tra ...

Importing .js files from the static folder in Nuxt.js: a step-by-step guide

I'm in the process of transitioning my website, which is currently built using html/css/js, to Nuxt.js so that I can automatically update it from an API. To maintain the same website structure, I have broken down my code into components and imported ...

Error: Unable to register both views with identical name RNDateTimePicker due to Invariant Violation

Encountering an issue while attempting to import: import DropDownPicker from 'react-native-dropdown-picker'; import DateTimePicker from '@react-native-community/datetimepicker'; <DropDownPicker zIndex={5000} ...

The ng-include feature seems to be malfunctioning

After building a basic web page using AngularJs, I ran into an issue when attempting to integrate header.htm into index.html - nothing was displaying in the browser. index.html <html> <script src="https://ajax.googleapis.com/ajax/libs/angul ...

Separate the elements with a delimiter

I am in the process of inserting various links into a division by iterating through a group of other elements. The script appears to be as follows $('.js-section').children().each(function() { var initial = $(this).data('initial'); ...

Triggering server-side code (node.js) by clicking a button in an HTML page created with Jade

I am currently working on developing a web application and have encountered an issue where I need to execute some server-side code when a button is clicked (using the onClick event handler rather than the Submit button). My tech stack includes Node.js, Exp ...

Angular does not seem to be identifying the project name as a valid property

After installing Angular materials using the CLI, I decided to check my angular.json file and encountered an error in the console stating that "Property MEAN-APP is not allowed". [The name of my Angular project is MEAN-APP] Here's a screenshot of the ...

Nested ng-repeats within ng-repeats

I have a question regarding the correct way to utilize an inner ng-repeat inside of an outer ng-repeat: Essentially, I am looking to implement something along these lines: <tr ng-repeat="milestone in order.milestones"> <td>{{mi ...

Utilizing Google APIs to split a route among multiple locations

I am facing a scenario where A laundry company operates from one shop location. The laundry company has 3 trucks available (n trucks). The laundry company needs to deliver washed clothes to multiple locations (n locations). Using the Google Directions AP ...

Is HTML5 Device Orientation the answer to a dependable compass system?

I am currently developing a project for mobile web that requires access to the compass direction of the user's device. At the moment, my code is quite basic, but here is what I have: var updateDirection = function (evt) { $("#dire ...

Navigating race conditions within Node.js++]= can be challenging, but there are strategies

In the process of developing a MERN full stack application, I encountered a scenario where the frontend initiates an api call to "/createDeckOfCards" on my NodeJS backend. The main objective is to generate a new deck of cards upon clicking a button and the ...