Getting JSON data with D3.js: A step-by-step guide

My JSON file is external and has a specific structure:

{
 data: [
       {
        0: 'cat',
        1: 232,
        2: 45
       },
       {
        0: 'dog',
        1: 21,
        2: 9
       },
       {
        0: 'lion',
        1: 32,
        2: 5
       },
       {
        0: 'elephant',
        1: 9,
        2: 4
       },
       ]
}

With d3.js, my goal is to extract the height data using key 2 for a bar chart. Here's what I have set up:

d3.select('#chart').append('svg')
    .selectAll('rect')
    .data(data)
    .enter()
    .append('rect')
    .attr('width', barWidth)
    .attr('height', function(d) {
        return d.data['2'];
    });

I can see the SVG canvas but am struggling to display the rectangles for the bar chart height. Any suggestions?

Appreciate any help!

Answer №1

To ensure the code functions as a standard bar chart, I made some adjustments. The key issue was utilizing d.data instead of simply d. Additionally, it's necessary to specify the x and y coordinates along with implementing alternating colors (or using padding with x) to prevent rectangle overlapping.

var width = 30;
var padding = 5;
var chartheight = 100;
d3.select('#chart').append('svg')
  .selectAll('rect')
  .data(data)
  .enter()
  .append('rect')
  .attr('width', width)
  .attr('height', function(d) {
    return d[2];
  })
  .attr('x', function(d, i) {
    return i*(width + padding);
  })
  .attr('y', function(d, i) {
    return chartheight - d[2];
  });

d3.selectAll('rect')
  .style('fill', function(d, i) {
    return i % 2 == 0 ? "#0f0" : "#00f";
  });

Answer №2

The variable d passed to your function represents the data being used for each item in the array:

.attr('width', function(d) {
    return d['2'];
});

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

When working with Angular Universal, using d3.select may result in a "reference error: document is not defined" in the server.js file

I'm currently working on an Angular project that uses server-side rendering to generate D3 charts. Each chart is encapsulated within its own component, such as a line-chart component which consists of TypeScript, spec.ts, HTML, and CSS files for rende ...

Using GraphicsMagick in combination with Node.js to upload a fresh image file to AWS S3: A step-by-step guide

I've encountered an issue while trying to upload images to S3 - phone images appear rotated due to EXIF data. To address this problem, I came across a tool called graphicsmagick which claims to remove EXIF data and resize images to 500px wide. However ...

Determine selected option in Radio Button

FORM : <form id="approvalPenambahanUserInt" name="approvalPenambahanUserInt" action="" method="post"> <div class="form-group"> <div class="col-sm-12"> <label for= ...

A step-by-step guide on utilizing the v-for index loop to showcase a nested JSON array

My JSON Array has the following structure: items: [ { ID: 11, UserID: "test.com", UserRole: "user", timeStamp: "2021-03-23T15:54:02.125578", dialogs: [ { "Bot" ...

Encountering an Uncaught TypeError while attempting to parse JSON using JavaScript

Recently, I've been working on parsing JSON in JavaScript {"success":{"id_user":"1", "username":"nasir", "password":"f30aa7a662c728b7407c54ae6bfd27d1"}} I successfully parsed the JSON using the following code snippet var obj = JSON.parse(result); ...

The AngularJS routing template fails to load

I am currently working on the app.js file: 'use strict'; var app = angular.module('app', [ 'auth0', 'angular-storage', 'angular-jwt', 'ui.router', 'Environment', ...

Angular allows for the creation of dynamic and interactive scenes using Canvas and Three.js

I am in the process of developing a collection of web apps within an Angular SPA. Each individual application is encapsulated within an Angular template, and when navigating between them, specific DOM elements are replaced and scripts from controllers are ...

I am interested in discovering the optimal method for loading a vehicle to its maximum capacity by exploring various combinations

My current task involves developing an algorithm to optimize the filling of a vehicle to its capacity based on various input combinations. Although the core problem has been resolved, the algorithm's efficiency is inadequate when dealing with a higher ...

Showing nested routes component information - Angular

I am working on a project that includes the following components: TodosComponent (path: './todos/'): displaying <p>TODO WORKS</p> AddTodosComponent (path: './todos/add'): showing <p>ADD TODO WORKS</p> DeleteTo ...

Convert JSON data into jQuery format, then present it in a list format using `<ul>` and

After making an ajax request, I receive a JSON string containing error messages regarding required form fields: first name, last name, email, usercode, password, password confirmation, and captcha. { "first_name":["The first name field is required."], " ...

Troubleshooting: jQuery addClass() function not functioning properly in conjunction with attr("href", something)

I am trying to implement a unique feature for a link using a Bootstrap button, where it only works on the second click. On the first click, the appearance of the link should change slightly. To achieve this, I am utilizing the .addClass(newClass), .removeC ...

Utilize Bootstrap tooltips to display live results fetched via an AJAX call

I have a bootstrap tooltip that I am trying to populate with data from an AJAX request. The text retrieved from the request should be displayed as the title property of the tooltip. Despite successfully executing the AJAX request, I am facing two issues: ...

Tips for safely executing an SQL query with electron.js

I have a new project where I need to interact with an SQL database on the local network, but it's not located on the same system I'm working on (not SQLExpress). So far, I've figured out how to collect user input on a webpage and send that ...

Issue with radio button click function not working on IE and Firefox

I am working with a form that has multiple inputs and radio buttons. Within the form, there are Yes & No radio buttons. When the "Yes" radio button is selected, additional data slides down below. HTML: <div class="item seperator first clearfi ...

Trigger the C# Click event with JavaScript fire function

Hi there, I could use a bit of assistance. My goal is to allow users to log in by hitting the "Enter" key on their keyboard. While I've successfully detected when the "Enter" key is pressed in my JavaScript code, I'm struggling with how to call m ...

Cut off all information beyond null characters (0x00) in Internet Explorer AJAX responses

When using Internet Explorer (IE6, IE7, and IE8), null characters ("0x00") and any subsequent characters get removed from ajax responses. Here's the code snippet that showcases a loop of AJAX requests: var pages = 10; var nextnoteid = 0; for (isub ...

When you reach the end of the page, the loadMore function is triggered multiple times

On my webpage, I have a list of profiles that are displayed. When the user reaches the bottom of the page, more data should be loaded through the loadMore function. While the loadMore function itself works correctly, I am facing an issue with the listener. ...

Using Jquery to encase an element in a div while scrolling down and removing it while scrolling up

After some experimentation, I've managed to wrap an element inside a div using jQuery. My next challenge is to wrap it as you scroll down and unwrap it as you scroll up. Do you think this is achievable? Although I have succeeded in wrapping it while ...

Is it possible to have two different actions with two submit buttons in PHP?

Here is my form tag: sample name:register.php page <form id="formElem" name="formElem" action="form10.php" method="post"> <input id="pd" name="pd" type="text" AUTOCOMPLETE=OFF /> <input id="pd1" name="fname" type="text" AUTOCOMPLETE=OFF /& ...

Having Trouble Receiving Desired Results with Ajax and JSONP

Testing jsonp for a new project. The html page features ajax, displaying a drop-down form and an empty table. The table cells will be populated based on the jsonp response fetched by ajax. The php response is hosted separately but doesn't seem to wo ...