Visualizing data with a grouped bar chart in D3.js

I am currently working on creating a vertical bar chart using D3.js, similar to the one shown in this https://i.sstatic.net/pig0g.gif
(source: statcan.gc.ca)

However, I am facing an issue as I am unable to display two sets of data for comparison. Following a tutorial from , I have created two classes "chart" and "chart1" with separate data but only the first set is being displayed. What could be causing this problem? Below is the code snippet: http://jsfiddle.net/x8rax/

<meta charset="utf-8">
<style>

.chart rect {
  fill: rgb(203, 232, 118);
}

.chart2 rect {
  fill: rgb(50, 50, 50);
}

.chart text {
  fill: white;
  font: 10px sans-serif;
  text-anchor: end;
}

</style>
<svg class="chart"></svg>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var data = [4, 8, 15, 16, 23, 42];


var width = 420,
    barHeight = 80;

var x = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([0, width]);


var chart = d3.select(".chart")
    .attr("width", width)
    .attr("height", barHeight * data.length);


var bar = chart.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight +")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 60);


bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });


// The actual data may not be relevant at this point.
</script>

<svg class = "chart2"></svg>
<script>
var data2 = [10, 10, 10, 10, 10, 10];

var width = 420,
    barHeight = 80;

var x2 = d3.scale.linear()
    .domain([0, d3.max(data2)])
    .range([0, width]);

var chart2 = d3.select(".chart")
    .attr("width", width)
    .attr("height", barHeight * data.length);

var bar2 = chart.selectAll("g")
    .data(data2)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight +")"; });

bar2.append("rect")
    .attr("width", x2)
    .attr("height", barHeight - 60);

</script>

Answer â„–1

Note: Successfully resolved the issue. The names of the second set of variables were missing in 3 locations:

1.

var chart2 = d3.select(".chart") (corrected to chart2)

2.

.attr("height", barHeight * data.length);
(corrected to data2)

3.

var bar2 = chart.selectAll("g") (corrected to chart2)

I have outlined the changes made below, including setting position:absolute on chart for overlapping with chart2.

Your code had some issues which I fixed by copying the functional parts and adjusting the data. I will review your entire code to identify and update any remaining problems.

For now, here is a functioning solution. To avoid confusion with naming, I used the same variable names for both charts since the svg elements don't retain variables after being appended.

var data = [4, 8, 15, 16, 23, 42];

var width = 420,
    barHeight = 80;

var x = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([0, width]);

var chart = d3.select(".chart")
    .attr("width", width)
    .attr("height", barHeight * data.length);

var bar = chart.selectAll("g")
    .data(data)
    .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight +")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 60);

var data = [10, 10, 10, 10, 10, 10];

var width = 420,
    barHeight = 80;

var chart = d3.select(".chart2")
    .attr("width", width)
    .attr("height", barHeight * data.length);

var bar = chart.selectAll("g")
    .data(data)
    .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + (i * barHeight + barHeight - 60 )  +")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 60);

http://jsfiddle.net/x8rax/6/

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

Troubleshooting "These dependencies were not found:" error message during deployment on Netlify, despite successful execution of yarn run serve on local machine

Currently, as I am creating a website using Vue.js, yarn, and Netlify. The build process works smoothly on my local machine when running yanr run build. However, upon deploying it through Netlify, an issue arises: 5:17:55 PM: failed during stage 'bui ...

Why is it that my jquery code seems to be struggling with calculating the count accurately?

I'm currently working on restricting keyword input on my website. My goal is to automatically add a 'span' tag to any keyword entered by a user, as shown in the example html code below. Although I can limit the number of words, the count i ...

Issue with Slick Grid not updating after Ajax request

I need to update the data on a slick grid when a checkbox is clicked, using an ajax call to retrieve new data. However, I am facing issues where the slick grid does not refresh and the checkbox loses its state upon page load. Jsp: <c:if test="${info ...

The displayed value in the text field remains constant even when the object's attribute is modified

My issue involves the Date Text Field component of Material UI. Whenever I pass an attribute from an object, the displayed value in the Text Field does not update even when the object attribute changes. const [data, setData] = useState({ title: new Da ...

[Vue alert]: "Maximum" property or method is not declared in the instance but is being referenced during the rendering process

Here is my custom Vue component: Vue.component("product-list", { props: ["products", "maximum-price"], template: ` <div> <div class="row d-flex mb-3 align-items-center p-3 rounded-3 animate__animate ...

Discover a JavaScript table using a for loop

Currently, I'm in the process of setting up a search bar within a table that has been populated by looping data retrieved from an API. My goal is to allow users to search for specific entries either by name or email. Unfortunately, I seem to be encoun ...

Why is the button missing from the codepen?

I attempted to recreate the code from this Codepen link: https://codepen.io/jakaric/pen/mjJQvg However, unlike what you see here (in the run result), the liquid "Pretty little button" is not showing up in my local files. On Codepen, there is no library me ...

Trigger an alert when a button is clicked and redirect the user to an newly opened tab

I recently created a button with a link that opens in a new tab. I also implemented some JavaScript to display an alert. Everything is working as expected, but after the user clicks "OK" on the alert, they remain on the same page. I would like to automati ...

Having trouble making md-data-table directives function properly

I'm struggling to incorporate the md-data-table library from https://github.com/daniel-nagy/md-data-table into my webpage. Despite loading the library in Chrome, none of the directives seem to be working. Here's a snippet of my code - can anyone ...

I am developing a quiz application using JavaScript, and I am wondering how I can smoothly transition from one question to the

I'm working on developing a quiz application and I'm facing an issue where my quiz is skipping question 2 when moving from one question to the next using the "next" button. I have a total of 3 questions in my quiz and for some reason, it jumps fr ...

Issue encountered while attempting to load external JSON file from server in AngularJS

Currently, I am attempting to load a JSON file from the server. Below is my services.js file: angular.module('starter.services', []) /** * A simple example service that returns some data. */ .factory('Friends', function($http) { ...

What is the process of utilizing marked plugins within a Vue3 project?

I attempted to integrate the marked plugin into my Vue.js applications. After installing [email protected], I did not encounter any issues during compilation. However, when I viewed the contents in the browser, nothing appeared. My Vue project was built u ...

The presence of an undefined variable in `esm.js` is resulting in an overwhelming amount of

After upgrading from Node v14 to Node v16, I encountered a strange error specifically when running node with node -r esm. The error message reads: ReferenceError: myVar is not defined This results in an extensive output of the esm.js module spanning 5000 ...

The 'Bfrip' button is missing from the DOM

Having some issues with displaying table content using DataTables. Everything seems to be working smoothly except for the Buttons, which are not appearing as expected. <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.1 ...

Navigate directly to a designated element in a React component without the need to scroll when clicking a link

When viewing a user's profile in React, clicking on an image currently scrolls to that specific image within the entire images page. However, I am looking to modify this behavior so that it navigates directly to the image element without any scrolling ...

Guide on converting arrays and sending this information in Node.js

I managed to retrieve quiz data and now I want to enhance it by mapping each answer to its respective quiz. I have a feeling that I should use something like forEach.push, but I haven't quite figured out the exact method... const API_KEY="https: ...

Tips on pairing elements from a ngFor processed list with another list using ngIf

If we have a list such as the one shown below: elements = [ { id: 1, name: "one" }, { id: 3, name: "three" }, { id: 5, name: "five" }, { id: 6, name: "six" }, ]; lists = [ { id: 5, name: "five" }, { id: 9, ...

Issue with IE7 when using JQuery to repopulate a <ul> unordered list: new elements showing up under previously hidden elements

Within this javascript snippet, I am utilizing the code below to clear out a list of countries within a <ul> element and then repopulate it (with a slight animation using jQuery's hide() function). The functionality works smoothly in Chrome and ...

Checking the security status of a PDF file in the web browser to determine if it

Within my platform, individuals have the ability to upload PDF files for others to access at a later time. In order to accommodate this functionality, I require that these PDFs are not secured or encrypted, and can be easily viewed by any user. To ensure ...

Tips for keeping a checkbox checked on page refresh in React JS

I am facing an issue where the checkbox, which was checked by the user and saved in local storage, is displaying as unchecked after a page refresh. Even though the data is stored in local storage, the checkbox state does not persist. The code I am using i ...