Designing a dynamic bar graph with intricate data sets through the utilization of D3

Exploring the world of D3 for the first time and following a tutorial on creating a flexible chart that adjusts to the width and height regardless of the number of bars ('The new Chart').

Struggling with using personal data, here's the simplified code from the tutorial for making a bar chart:

var w = 500;
var h = 100;
var barPadding = 1;

var data = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
                11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];

//Create SVG element
var svg = d3.select("body")
            .append("svg")
            .attr("width", w)
            .attr("height", h);

svg.selectAll("rect")
   .data(data)
   .enter()
   .append("rect")
   .attr("x", function(d, i) {
        return i * (w / data.length);
   })
   .attr("y", function(d) {
        return h - (d * 4);
   })
   .attr("width", w / data.length - barPadding)
   .attr("height", function(d) {
        return d * 4;
   });

The issue might be related to the 'data.length' segment in the tutorial's code:

.attr("x", function(d, i) {return i * (w / data.length);

Alternatively, it could be how I'm accessing 'time' from my dataset. Here's my code snippet:

<div id="chart">
<svg width="800" height="600"><g class="group"></g>
</svg>
</div>

var w = 500;
var h = 100;
var barPadding = 1;

var data = [
{"name": "The Kings speech", "time": 118},
{"name": "Slumdog Millionaire", "time": 120},
{"name": "Shakespeare in Love", "time": 122},
{"name": "Chariots of Fire", "time": 123},
]

d3.select('svg g.group')
.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', function(d, i) {return i * (w / data.length)})
.attr('y', function(d) {return h - d['time'];})
.attr('width', w / data.length - barPadding)
.attr('height', function(d) {return d['time'];})

Seeking guidance to overcome this hurdle, any help would be greatly appreciated! Thank you.

Answer №1

There is a mistake in your code, the semicolon should be placed outside of ['time']:

.attr('y', function(d) {return h - (d['time';])})

The correct version is:

.attr('y', function(d) {return h - d['time'];})

To identify errors, make sure to check the error messages displayed in the developer console.

After updating your question:

Wrap your javascript code between

<script type="text/javascript">
and </script>

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

Experiencing difficulties with setting up SearchApp

Issue: I am encountering a problem with my cloudant account after attempting to install the SearchApp from this link. The installation process was successful, but when I try to use the search functionality on the site, nothing happens. Query The website ...

The system has encountered an issue: "EntityMetadataNotFound: Unable to locate metadata for the entity named 'User

Just wanted to reach out as I've been encountering an issue with my ExpressJS app recently. A few days ago, everything was running smoothly without any errors. However, now I'm getting a frustrating EntityMetadataNotFound: No metadata for "User" ...

Is there a way to prevent the omission of zeros at the end in JavaScript when using Number.toString(2)?

I am facing an issue while trying to reverse a 32-bit unsigned integer by converting it to a string first. The toString(2) function is causing the zeros at the end to be omitted, leading to incorrect output. This is my code: var reverseBits = function(n) ...

What could be causing the malfunction of the map function, despite the code appearing to be correct?

I have encountered an issue in my React functional component where I am trying to display a list of notifications. The useEffect() function is being called to generate the "data" which should then be displayed on the page. The code seems to be running fine ...

Using JavaScript/JQuery to Access an External SQLite Database

Is there a way to incorporate my own SQLite database into a website using JavaScript and JQuery? I've searched for examples but have yet to find any helpful articles on the topic! ...

Having trouble deciphering the logic behind my bug detection process in the Three.js Verlet Cloth Simulation on GPU

I'm facing difficulty grasping the logic I am working on with Three.js and the GPUComputationRenderer developed by yomboprime. (https://github.com/yomboprime/GPGPU-threejs-demos/blob/gh-pages/js/GPUComputationRenderer.js) My goal is to create a simp ...

What is the best way to display the output of a node-mssql statement using Jade?

I have a Node.js server set up with Express and Jade. Upon an HTTP request, the server will run the following function: function home(req, res) { res.render("site/index", {recordset: recordset}); //rendering the Jade template } Now, I want to pass an ...

Display a message indicating no data is available if the specified text is not found within the div

In the code snippet below, there is an input element followed by a div containing multiple child elements: <input type="text" onkeyup="filter()" id="filter_data"> <div id="body"> <div class="child"> Text 1 </div> <div class ...

Jump to Anchor when Page Reloads

Hey there! I'm currently developing a gallery script and I'm trying to figure out how to automatically position the page to the top of a specific anchor when it is loaded. I attempted to use the following code: <script>location.href = "#tr ...

Reflection effect on the ground in three.js

Is there a way to achieve the same effect without duplicating spheres? I attempted to replicate the functionality, but the reflections appear too large :/ var groundTexture = THREE.ImageUtils.loadTexture( "files/checkerboard.jpg" ); groundTexture.wrapS = ...

Opting for fetch over jQuery's ajax for making successful GET requests to an API

Recently, I found myself in a situation where I needed to convert a function that uses a remote API from returning a callback to returning a Promise. This change presented an opportunity for me to also switch from using $.ajax to fetch, since fetch already ...

arranging a collection of images based on their values in increasing order

cardShop is a container with various images, each with its own unique ID and value attribute. These values consist of two numbers separated by a comma, such as 2000,500 or 1500,200. My goal is to sort these images in ascending order based on the first numb ...

When using a React Router path variable along with other paths, React may have difficulty distinguishing between them

Setting up react router in my project to differentiate between user username variables and other paths is proving challenging. For instance: baseUrl/admin baseUrl/daniel Currently, React is unable to distinguish between the two. My intention is to query ...

Secure User Authentication using HTML and JavaScript Box

In the given code, I am attempting to implement a functionality where a message is displayed next to the select box if it does not have a value of male or female. This message should not be shown if one of these values is selected. However, this feature ...

Clipboard information inserts arbitrary line breaks into text

Whenever I attempt to retrieve data from the clipboard using event.clipboardData.getData('text/html'), the resulting HTML includes line breaks that are not supposed to be there. Here is the current output: <p class=Tabeltekst style='ms ...

Obtaining the ID of a div element and showing it in an alert message

Apologies for the simple query. Looking at the HTML snippet below: <div id="Jessica"> Alba. </div> and the following JavaScript code: window.onload= function() { var hot= document.getElementById("Jessica"); hot.onclick=function() { ...

I'm encountering issues with adding a div element using Jquery

I've been attempting to insert a div using jQuery, following the code example below. Unfortunately, it's not working as expected. jQuery: $('<div />', { $('<img />', { "src": "/Pages/Images/calendar.png").add ...

Using React - What is the best way to invoke a function from within a different function?

Imagine this scenario: class Navigation extends React.Component { primaryFun() { console.log('funn') } secondaryFun() { this.primaryFun(); } } I assumed that calling primaryFun within secondaryFun would work as expected, but instead I rec ...

The error function is consistently triggered when making an Ajax POST request, even though using cURL to access the same

I have been using Ajax's POST method to retrieve a JSON response from the server. However, whenever I click the button on my HTML page, the Ajax function always triggers the error function, displaying an alert with the message "error." Below is the co ...

Retrieving user data using axios in React to fetch user_id information

I'm currently working on a React project where I have created a simple list and I am fetching data using axios. Here's a snippet of my code: https://codesandbox.io/s/old-worker-6k4s6 import React, { useState, useEffect } from "react"; ...