Creating a visual representation of data using a column graph with a datetime x-axis in D

As someone new to d3.js, I attempted to create a column graph with a datetime x-axis. Unfortunately, I seem to have made a mistake in my code. Any help in identifying and rectifying the error would be greatly appreciated. Thank you in advance for any assistance.

var data = [{
                "time": "01:00:00",
                "total": 1
            }, {
                "time": "01:05:30",
                "total": 2
            }, {
                "time": "02:10:00",
                "total": 1
            }, {
                "time": "03:15:30",
                "total": 3
            }, {
                "time": "04:25:30",
                "total": 1
            }, {
                "time": "07:55:15",
                "total": 4
            }, {
                "time": "12:18:00",
                "total": 1
            }, {
                "time": "17:00:00",
                "total": 5
            }];

            var margin = {
                top: 40,
                right: 40,
                bottom: 40,
                left: 40
            },
            width = 800,
            height = 500;

            var today = new Date();
            today.setHours(0, 0, 0, 0);
            var todayMillis = today.getTime();

            data.forEach(function(d) {
                var parts = d.time.split(/:/);
                var timePeriodMillis = (parseInt(parts[0], 10) * 60 * 60 * 1000) +
                                       (parseInt(parts[1], 10) * 60 * 1000) + 
                                       (parseInt(parts[2], 10) * 1000);

                d.time = new Date();
                d.time.setTime(todayMillis + timePeriodMillis);
            });

            var x = d3.time.scale()
                .domain(d3.extent(data, function(d) { return d.time; }))
                .nice(d3.time.day, 1)
                .rangeRound([0, width - margin.left - margin.right]);

            var y = d3.scale.linear().range([height - margin.top, margin.bottom]).domain([0,
                     d3.max(data, function (d) {
                     return d.y;
                      })
                    ]);

            var xAxis = d3.svg.axis()
                .scale(x)
                .orient('bottom')
                .ticks(d3.time.hour, 2)
                .tickFormat(d3.time.format('%H:%M'))
                .tickSize(5)
                .tickPadding(8);

            var yAxis = d3.svg.axis()
                .scale(y)
                .orient('left')
                .tickPadding(8)
                .tickSize(5)
                .tickSubdivide(true);

            var svg = d3.select('#plot_container').append('svg')
                .attr('class', 'chart')
                .attr('width', width)
                .attr('height', height)
                .append('g')
                .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');

            svg.selectAll('.chart')
                .data(data)
                .enter().append('rect')
                .attr('class', 'bar')
                .attr('x', function (d) {
                    return x(d.time);
                })
                .attr('y', function (d) {
                  return y(d.total);
                })
                .attr('width', 0)
                .attr('height', function (d) {
                  return ((height - margin.bottom) - y(d.y));
                })

            svg.append('g')
                .attr('class', 'x axis')
                .attr('transform', 'translate(0, ' + (height - margin.top - margin.bottom) + ')')
                .call(xAxis);

            svg.append('g')
                .attr('class', 'y axis')
                .attr('transform', 'translate(' + (margin.left) + ',0)')
                .call(yAxis);

Answer №1

There are a few issues in your code that need addressing:

  • The bar width is set to zero;
  • The y scale relies on an unknown value (d.y);
  • The bar height also uses the unknown value (d.y);
  • The y scale has margin.bottom and margin.top in the incorrect position;
  • The y axis translation is incorrect.

To fix these problems, you can refer to this updated code: https://example.com/codefix123

While there are still more issues to address, this should get you started on the right track.

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 selecting an input within a div, the Angular onblur function is behaving erratically

How can I prevent the div from closing when I click on an input inside it after setting a tabindex to the div and closing it on blur? Solution for app.component.html: <button (click)="openToggle('toggle1')">Toggle 1</button> ...

Managing two separate instances with swiper.js

Currently, I have set up two instances of swiper.js and I am looking to scroll both while interacting with just one of them. Update: My primary objective is to replicate the core functionality seen on the swiper homepage. Update 2: I came across this lin ...

Make sure to save the HTML content after we make an AJAX call to retrieve it

Is there a way to call an HTML file using Ajax and then save the response as an HTML file in a specific location? I have been trying to make an Ajax call using jQuery, like shown below: $.ajax({ type: "POST", url: "../../../project/html/T ...

What is the method for retrieving profile data using Google Oauth2 passport?

Display the name of the currently logged-in user in the footer of the index page. Google login routes router.get("/login/google", passport.authenticate('google', { scope: [ 'email', 'profile' ] })); router.get("/login/go ...

"Attempting to send JSON data via JsonResult is unsuccessful when trying to send a JSON object directly or using JSON

In my project, I have a class that looks like this: I've created a JsonResult method in the controller which takes an object of this class as a parameter: [HttpPost] public JsonResult NewAreaCode(AreaCode model) { return Json ...

Could it be that my DataTable sourced through ajax is not parsing as expected?

When troubleshooting, the first step is usually to identify the error at hand... DataTables alert: tableid=myTable - Encountered unknown parameter 'Name' for row 0, column 0. For further assistance regarding this issue, please refer to http://da ...

When using `console.log`, the object is displayed correctly. However, an error occurs when

Here is the code I've been working on: function parseJSONData(jsonData){ var property, type, name, identifier, comment, content; for(property in jsonData){ switch(property){ case "type": type = jsonData[ ...

Utilizing Ajax in PHP to Upload Files

I'm encountering an issue while attempting to upload a file and send it via AJAX. The error message I am receiving is as follows: Notice: Undefined index: xlsFile in Here is the code snippet: HTML FORM : (this form is within a Modal Popup) <f ...

Difficulty in handling errors within an Express application

Hey there, I'm facing an issue with catching errors in my express.js application. The problem arises when the next function is called within the controller. For some reason, the error middleware does not execute as expected and I'm unsure why thi ...

What happens when arithmetic operators are applied to infinity values in JavaScript?

Why do Arithmetic Operators Behave Differently with Infinity in JavaScript? console.log(1.7976931348623157E+10308 + 1.7976931348623157E+10308)//Infinity console.log(1.7976931348623157E+10308 * 1.7976931348623157E+10308)//Infinity console.log(1.797693134 ...

"Efficiently handle JSON and binary data passing with the enhanced functionality of Express Body Parser

Within my express app router, I have routes set up to handle both POST requests with JSON data and binary data. The issue arises when I use body parser to parse the JSON data, as it incorrectly interprets the binary data as JSON and causes errors during th ...

Submitting dataURL via Ajax using multipart/form-data

I'm currently working on a program that is responsible for extracting a dataURL from a canvas element and then transmitting it to the server side for conversion back into a JPG file. Now, my next step involves retrieving this image from the server pro ...

Accessing the JSON file from the Google Maps Places API using either JavaScript or PHP

In the midst of developing an application, I am working on fetching a list of places near a specific latitude and longitude. After obtaining an API key, inputting it into the browser URL successfully retrieves a JSON file containing the desired places dat ...

Utilizing either Maps or Objects in Typescript

I'm in the process of developing a simple Pizza Ordering App. The concept is, you select a pizza from a list and it's added to a summary that groups all the selections together. Here's how I want it to appear: Pizza Margarita 2x Pizza Sala ...

Interactive hover effect in JavaScript displays a larger version of other thumbnails when hovering over a dynamically loaded thumbnail image, instead of its own full-size image

I recently began teaching myself PHP and Dreamweaver with the help of a video tutorial on building data-driven websites using Dreamweaver. My goal is to create a dynamic table with 6 columns and 20 rows. column1 | column2 | column3 | colu ...

The action is not being added to the HTML when the click event is triggered

I'm developing a GIF generator, with the aim of generating clickable buttons that will dynamically add 10 gifs based on the search term to the page. Although the click event is triggering the console log, it's not adding divs with gif images and ...

Stop unauthorized direct access to PHP forms and only allow submission through AJAX requests

I have set up a script that sends an email notification whenever someone comments on my Facebook comment box. The script uses FB.event.subscribe to trigger an AJAX call to mail.php on my server, which then sends an email to my address. How can I enhance ...

SignalR enables the display of identical dashboard data pulled from queries on various browsers. By utilizing SignalR/hub, MVC, and C#.NET, the data can

Encountering an issue with my signalr/hub while fetching dashboard data. I'm using 2 browsers to access data based on dates. However, when searching for July on browser 1 and then switching to another month on browser 2, the data in browser 1 gets upd ...

Submit the form only when the specified conditions are met, otherwise return

Is there a way to submit a form after it has been prevented from submitting? I've searched for solutions on StackOverflow but haven't found one that works for me. Below is the code snippet in question: $(function(){ $("#loginform").submit(f ...

Each JSON entry deserves its own dedicated page

Recently, I've started using Contentful and have already created a few entries. Now, my goal is to create a simple dynamic page with subpages - essentially like a portfolio. What I envision is an index page with links to inner portfolio pages, each co ...