Creating a Bar Chart in d3js with time on the x-axis and one or multiple sets of numerical data on the y-axis: a step-by

My webpage structure is as follows:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link href="css/style.css" rel="stylesheet" />
</head>
<body>
    <div id="title">Statistics</div>
    <div id="chart"></div>

    <script src="js/libs/jquery.min.js"></script>
    <script src="js/libs/d3.min.js"></script>

    <script src="js/src/main.js"></script>
    <script>
        $(function() {
           HU.init(); 
        });
    </script>
</body>
</html>

This is the JavaScript code written for displaying data:

var HU = (function() {

var data = [
        {"time": "13:24:20", "level_1": "5553", "level_2": "4682", "level_3": "1005"},
        {"time": "14:24:20", "level_1": "6553", "level_2": "5682", "level_3": "2005"},
        {"time": "15:24:20", "level_1": "7553", "level_2": "6682", "level_3": "3005"},
        {"time": "16:24:20", "level_1": "8553", "level_2": "7682", "level_3": "3131"},
        {"time": "17:24:20", "level_1": "9953", "level_2": "5500", "level_3": "5005"},
        {"time": "18:24:20", "level_1": "8565", "level_2": "7682", "level_3": "6005"},
        {"time": "19:24:20", "level_1": "7753", "level_2": "4546", "level_3": "4405"}
    ];

init = function() {


    var margin = {
            top: 10, 
            right: 10, 
            bottom: 30, 
            left: 50
        },
        width = 950 - margin.left - margin.right,
        height = 500 - margin.top - margin.bottom;

    var parseDate = d3.time.format("%H:%M:%S").parse;

    var x = d3.time.scale()
            .range([0, width]);

    var y = d3.scale.linear()
            .range([height, 0]);

    var xAxis = d3.svg.axis()
            .scale(x)
            .orient("bottom")
            .tickFormat(d3.time.format(("%H:%M:%S")));

    var yAxis = d3.svg.axis()
            .scale(y)
            .orient("left");

    var svg = d3.select("#chart").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0, " + height + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);

    var bars = svg.selectAll("rect")
        .data(data)
        .enter().append("rect")
        .attr("x", function(d) { return x(parseDate(d.time)); })
        .attr("y", function(d) { return y(d.level_1); })
        .attr("width", 15)
        .attr("height", function(d) { return height - y(d.level_1); })
        .style("fill", "steelblue");

};



return {
    init: init
};

})();

I am trying to display time from JSON on the X-Axis, and show all three levels overlapping each other on the Y-Axis. The CSS styling for this page is as follows:

body {
  font: 300 78px Helvetica Neue;
}

#title {
  font-size: 50px;
  margin: 20px;
  text-align: center;
  color: steelblue;
}

#chart {
  margin: 20px auto;
  position: relative;
  width: 900px;
  height: auto;
}

svg {
  font: 10px sans-serif;
}

.x.axis path {
  display: none;
}

.y.axis line {
  stroke: #fff;
  stroke-opacity: .4;
  shape-rendering: crispEdges;
}

.y.axis .zero line {
  stroke: #000;
  stroke-opacity: 1;
}

rect {
  fill-opacity: 0.9;
  fill: #777;
}

rect:first-child {
  fill: steelblue;
}

Any suggestions on how I can achieve this? Thank you in advance!

Answer №1

Ensure to specify the domain values for the scales.

var xScale = d3.time.scale().domain(d3.extent(data, function(d) { return parseDate(d.date); }))
        .range([0, width]);

var yScale = d3.scale.linear().domain(d3.extent(data, function(d) { return d.value; }))
        .range([height, 0]);

View the full example on jsfiddle here.

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

if a condition is not being properly assessed

Currently, I am working on a $.ajax call to retrieve data in JSON format. Within this JSON data, there is an element called "status." My code snippet checks if the value of `data.status` is equal to "success" and performs some actions accordingly. Despite ...

What is the best way to determine the total number of elements within this JSON data structure?

Is there a way to determine the number of elements in a JSON object using JavaScript? data = { name_data: { 35: { name: "AA", }, 47: { name: "BB", }, 48: { name: "CC", ...

Retrieve data from the component within anonymous middleware in NuxtJS

Is there a way to retrieve the component data (like infos, similarPosts shown in this example) from an anonymous middleware within a Nuxt.js application? ...

Top method for detecting errors in Models? (Node.js + Sequelize)

Looking for a straightforward method to catch errors in an API using Node.js and Sequelize models? Take a look at this code snippet which utilizes async-await: const router = express.Router() const { Operations } = require('../models') router.po ...

The child process is arriving empty, which is causing a requirement

Every time I try to use var childprocess = require('child_process'); I keep getting a blank result. When I attempt var childProcess1 = require('child_process').spawn; it returns as undefined, and, var childProcess2 = require(&a ...

Sending data from a JavaScript variable to PHP within the same page

I've been attempting to transfer a JavaScript variable to PHP within the same page without success. I have tried different codes but none seem to be working as expected. Here is the current code snippet: function init(e){ $('#DeleteDaily' ...

What is the method for a JavaScript program to determine if a global property name has been defined according to the ECMA-262 standard

Imagine creating a function called checkIfEcmaGlobal which would return true for recognized names of ECMA-262 globals. $ node > checkIfEcmaGlobal('Array') true > checkIfEcmaGlobal('process') false What approach could be taken to ...

Error in ReactJs production code: ReferenceError - the process is undefined

Having some trouble with my ReactJs production code not recognizing environment variables. The error message reads: Uncaught ReferenceError: process is not defined <anonymous> webpack://testProject/./src/agent.js?:9 js http://localhost:8080/s ...

Possible solutions for AngularJS using ng- tags

I absolutely love incorporating AngularJs into my Multiple Pages Laravel Application. However, using the Laravel Blade Template Engine has made me reconsider adding Angular Tags to clutter my blade templates. For instance <div ng-controller="TodoCont ...

Instructions on utilizing the signUp() function in Supabase for including extra user details during the registration process

My latest project involves building a Vue.js application with authentication using Supabase. I've been trying to implement the signUp() method from Supabase in order to collect extra user data during the sign-up process. In my code, I added a property ...

Creating a JSON array using looping technique

I am attempting to construct a JSON array using a loop where the input className and value will serve as the JSON obj and key. However, I am facing difficulties in creating one and cannot seem to locate any resources on how to do so. Below is an example sn ...

Battle between Comet and Ajax polling

I'm looking to develop a chat similar to Facebook's chat feature. Using Comet would require more memory to maintain the connection. There seems to be a latency issue when using Ajax polling if requests are sent every 3-4 seconds. Considering t ...

Angular can help you easily convert numbers into a money format

I need assistance in converting a number to Indian currency format. Currently, I have attempted the following: http://plnkr.co/edit/lVJGXyuX0BMvB9QUL5zS?p=preview function formatMoney(credits) { console.log(credits+'credits'); var last ...

The function d3.select is unavailable, however d3 has been successfully imported as (* as d3)

I am currently facing some challenges with D3. I have tried implementing both of these methods individually, but unfortunately, I am encountering the same error. import * as d3 from "d3"; const d3 = require("d3"); Here is the specifi ...

Collaborate and apply coding principles across both Android and web platforms

Currently, I am developing a web version for my Android app. Within the app, there are numerous utility files such as a class that formats strings in a specific manner. I am wondering if there is a way to write this functionality once and use it on both ...

Tips for sending a PDF created with jsPDF as an attachment in an email using asp.net c#

I'm wondering if there's a way to attach a PDF file that was generated using jsPDF and email it in asp.net C#? This is the code snippet I have in c#: MailMessage message = new MailMessage(fromAddress, toAddress); message.Subject = subj ...

What is the best way to pass values between JSP Expression Language and Javascript?

I have a request object with the following content: List<Integer> list What is the best way to loop through this list using JavaScript? I am interested in obtaining the values of each element within the list. Note that these list values are not cu ...

Transmitting an item through a GET request using parameters in Postman

Recently joining this site, I created my user account just a few days back. I am attempting to send a GET request using Postman, but it's not working as expected. There seems to be some issue. Here is what I am trying to accomplish: Using Postman: ...

Load media upon the click of an image

I'm currently in the process of designing a team page for our website. Each team member's photo is displayed in a grid layout, with two boxes positioned below containing various content. Box 1: This box consists of basic text information. Box 2: ...

What is causing the TypeScript error in the MUI Autocomplete example?

I am attempting to implement a MUI Autocomplete component (v5.11) using the example shown in this link: import * as React from 'react'; import TextField from '@mui/material/TextField'; import Autocomplete from '@mui/material/Autoco ...