Combining data using D3's bar grouping feature

I'm currently exploring ways to group 2 bars together with some spacing between them using D3. Is there a method to achieve this within D3? I found inspiration from this example.

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

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

d3.select(".chart")
  .selectAll("div")
    .data(data)
  .enter().append("div")
    .style("width", function(d) { return x(d) + "px"; })
    .text(function(d) { return d; });

Your input is greatly appreciated. Thank you.

Answer №1

Check out the final outcome: https://codepen.io/example-code/pen/pojeQrv

To achieve this, some modifications were made to your style function:

.style("width", function(d,i) { 
  if(i % 2 == 0 && i != 0){
    d3.select(this).style("margin-top", 7+"px")
  }else if(i == 0){}

  return x(d) + "px"; })

You have the option to adjust the modulo factor to change the group sizes. For instance, for groups of 4:

if(i % 4 == 0 && i != 0){

Answer №2

The concept here is to organize the bars into a DIV container and create separation between the group div elements with margin or padding.

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

let groupedData=[];
for(let i=0;i<data.length/2;i++){
  groupedData[i]={
    "first":data[i*2],
    "second":data[i*2+1]
  };
}
console.log(groupedData);
const xScale = d3.scaleLinear()
    .domain([0, d3.max(data)])
    .range([0, 420]);

barsEnter=d3.select(".chart")
  .selectAll("div.bars")
    .data(groupedData).enter().append('div').attr('class','bargroup');
  barsEnter.append('div')
            .style("width", function(d) { return xScale(d.first) + "px"; })
            .text(function(d) { return d.first; });
barsEnter.append('div')
            .style("width", function(d) { return xScale(d.second) + "px"; })
            .text(function(d) { return d.second; });

The CSS has been updated as follows:

.chart .bargroup{
margin-bottom:10px;
}
.chart .bargroup div {
  font: 10px sans-serif;
  background-color: steelblue;
  text-align: right;
  padding: 3px;
  margin: 1px;
  color: white;
}

You may access the updated code through the link provided below:

http://codepen.io/anon/pen/YqJpzK

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

Session storage conditional statement is not behaving as anticipated in JavaScript

I am currently working on session storage functionality where a user must select one radio button on the first page and then click the next button. On the second page, a div is supposed to show up. On the first page, I have created a function with a set of ...

A dynamically-generated dropdown element in the DOM is being duplicated due to JavaScript manipulation

Currently, I am dynamically adding a dropdown element to the page using javascript. The goal is for this dropdown to modify the properties displayed on a map. However, when attempting to add the element after the map loads, I encounter an issue where the d ...

Expand the width and include a placeholder in mat input field for Angular version 5

Currently utilizing a mat input with the code provided, presenting a similar appearance to the screenshot below. I am looking to add a placeholder that disappears once the user begins typing. However, in my current setup, the text shifts upward and floats ...

Transforming a string representation of a nested array into an actual nested array with the help of JavaScript

My database stores a nested array as a string, which is then returned as a string when fetched. I am facing the challenge of converting this string back into a nested array. Despite attempting to use JSON.parse for this purpose, I encountered the following ...

How can I simulate pressing the ENTER key in Selenium without selecting any element?

Having trouble using the firefox selenium plugin and sending the enter key after pasting text? The ENTER key press should not interact with any other element on the page, just a simple 'dumb' ENTER key press. error [error] Element name=code not ...

Modifying the 'child' node within a JSON object

Exploring the implementation of d3s Collapsible tree using a custom node hierarchy. My dataset structure deviates from the norm, for example: http://jsfiddle.net/Nszmg/2/ var flare = { "Name": "Example", "members": [ { "BName":"Ja", ...

Execute the function numerous times that is associated with an asynchronous function in JavaScript

I am currently working on two functions: one is asynchronous as it fetches data from a CSV file, and the other function renders a list of cities. The CSV file contains information about shops located in various cities. My goal is to display a list of cit ...

Deactivate radio buttons when the table value is greater than or equal to one

On my webpage, there are radio buttons for 'Yes' and 'No'. When 'Yes' is selected, a hidden <div> appears where users can fill in fields. Upon clicking the 'Add' button, the information is displayed in a table. ...

JSON Generator's date formatting convention

One method I use to create a JSON object is through JSON-GENERATOR I prefer the date to be formatted like this: 2017-12-31 [ '{{repeat(5, 7)}}', { equityPriceList: [ { date:'{{date(new Date(1970, 0, 1), new Date(),[DD ...

Should code in Vuejs be spread out among multiple components or consolidated into a single component?

After spending a significant amount of time working with Vue, I find myself facing a dilemma now that my app has grown in size. Organizing it efficiently has become a challenge. I grasp the concept of components and their usefulness in scenarios where the ...

Is there a way to trigger a JavaScript function upon checking a checkbox?

Is there a way to trigger a Javascript function when a checkbox within a gridview is checked? protected void ChangeStatusSevenDays_Click(object sender, EventArgs e) { for (int i = 0; i < grdImoveis2.Rows.Count; i++) { GridViewRow RowVie ...

Continuously refresh the if/else statement

I'm currently facing an issue with my jQuery code regarding a responsive navigation bar. I am trying to add a class called 'mobile' to the navigation bar when it reaches close to the logo. Below is the snippet of my code: function respon ...

What sets apart elevation from z-index in material-ui?

As I delved into the material-ui documentation, I came across an interesting snippet: Various components in Material-UI make use of z-index, a crucial CSS property that aids in organizing content along a third axis. Material-UI employs a predefined z-in ...

Refresh database post drag and drop operation

I am seeking a way to update a "state" SQL row after dragging an element between the "DZ", "WT", and "ZK" divs. Below is a snippet of my code: SQL queries: $sql = "select * from tasks where login = '$user_check' AND state = 1"; $sqlDodane = mys ...

Creating a HTML5 canvas animation of an emoticon winking to add a fun touch to your

Currently, I am facing a challenge in animating an emoticon that was initially sketched on canvas. While following a tutorial to implement draw and clear animations using frames, I haven't been able to achieve the desired outcome. With 6 frames of the ...

Learn how to display each element in a list one by one with a three-second interval and animated transitions in React

Let's consider a scenario where we have a component called List: import React, { Component } from 'react'; class List extends Component { constructor() { super(); this.state = { list: [1, 2, 3, 5] } ...

What steps are needed to switch colors after a loop has been clicked?

I have a loop setup like this: data: { show: false } .test { hight: 10px; background-color: red; } .test2 { hight: 15px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div v-for="value in da ...

Creating a fullscreen layout in HTML with specific minimum and maximum widths

Looking to create a layout where one item takes up 1/3 of the screen-width with a minimum width of 500px and a maximum width of 700px, while another item fills the rest of the screen. Ideally, setting a width of 66% should work, but issues arise when the h ...

Ways to integrate a security protocol with a graphql resolver

I'm currently diving into the world of graphql and I'm facing a challenge with incorporating an authentication/authorization system into my project. I stumbled upon an example on Medium, but I'm struggling to grasp how a guard connects with ...

Supply a JSON parameter as a variable into the .load() function

When a button is clicked, I am attempting to load a page using the .load() method with a POST request. The URL parameters are generated and displayed as JSON formatted in the button attribute btn-url. Problem: The parameter is not being passed to the .loa ...