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

creating a Vue app using Node results in an HTML page with no content due to syntax errors

After creating a VueJs page using the CLI, I wanted to share it with others who might not have Vue CLI or Node installed. Just like opening .html files in a browser, I tried to open the index.html file after building it. However, when I opened the file, a ...

What is the best way to retrigger an ajax request in jQuery after it encounters an error?

In my JavaScript code, I have an AJAX request that communicates with a Rails controller to send data. If the controller detects duplicate information already in the database, it returns an 'Unprocessable Entity' error. I am looking to implement ...

Nock is capturing my request, however, my AJAX call is encountering an error

I am currently conducting a test on an AJAX request using the XMLHttpRequest method: export default function performTestRequest() { const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://example.com/service'); xhr.onload = ( ...

Maximizing Efficiency: Sending Multiple Responses during computation with Express.js

Seeking a way to send multiple responses to a client while computing. See the example below: app.get("/test", (req, res) => { console.log('test'); setTimeout(() => { res.write('Yep'); setTime ...

organizing strings in alphabetical order using TypeScript

My md-collection is set up to display a list of emails like this: <md-collection-item repeat.for="u of user" class="accent-text"> <div class="row"> <di ...

Change numbers into a comma-separated style containing two decimal points using javascript

I have been working on a JavaScript function to convert numbers into a comma-separated format with two decimal places: Here is my current code snippet: Number(parseFloat(n).toFixed(2)).toLocaleString('en'); The issue with this code is that it ...

What could be causing the submenus in my intricate menu component to lose focus when input is entered?

I'm currently working on developing a menu using the MUI Menu component. The goal is to have a popup input control (such as Autocomplete, TextField, Select, or a custom form) appear when a menu item is clicked, based on the choice made from the menu. ...

Content Security Policy directive violation: Chrome extension policy error occured due to refusal to execute inline event handler

I've been working on a chrome extension to perform a simple task, but I've hit a roadblock with one line of HTML code that's causing issues with setting the correct permissions. Despite my efforts, I'm stuck on what exactly needs to be ...

Tips on personalizing the FirebaseUI- Web theme

Can someone help me find a way to customize the logo and colors in this code snippet? I've only come across solutions for Android so far. if (process.browser) { const firebaseui = require('firebaseui') console.log(firebaseui) ...

Utilize JavaScript to communicate with the backend server

I'm embarking on my first Cordova application, utilizing HTML, CSS, and JavaScript. My current objective is to trigger a local server call upon button click, with the intention of logging something to confirm functionality. However, I'm encounter ...

How can I receive user input in JavaScript while incorporating three.js?

I am currently exploring the functionalities of this three.js example () and I am interested in enabling users to input specified X, Y, and Z positions for boxes dynamically. Initially, I considered utilizing a JavaScript prompt like below: var boxes = p ...

How can you set the listbox in Sumo Select to always be open?

Is there a way to ensure the listbox is always open by default, as if the user had clicked? ...

Fully responsive header designed for optimal experience at any screen height

I am facing issues with the header and cannot seem to find a solution. My goal is to make the header span 100% of the window screen height. I need a responsive header that adjusts to 100% height, and when resizing for a smaller viewport, nothing should sho ...

Firebase Cloud Functions - Deleting the eldest offspring

I have created an onWrite cloud function that listens for updates made by a user. My goal is to delete the oldest child if there are more than three children present in the database. Here's where I currently stand: exports.removeOld = functions.datab ...

Steps for transitioning a VUE JS project to TypeScript

Is it possible to transition a VUE JS project from JavaScript to TypeScript without rewriting everything? I heard from a friend that it can be done through the VUE CLI, but I haven't been able to find any documentation or articles on this method. Has ...

Exploring the process of querying two tables simultaneously in MySQL using PHP

I currently have a search box in my PHP file that only searches from the "countries" table. However, I also have another table called "continent" and I would like the search box to retrieve results from both the "countries" and "continent" tables. Here is ...

Directing to index.html using ExpressJS

JS, I am working on an express app that has various routes defined. However, I am facing an issue where if the router does not match any route, it displays index.html instead of redirecting to a specific route like '/*' as I expected. I am unsu ...

What is the best way to extract multiple values from a JavaScript variable and transfer them to Node.js?

Script JavaScript script snippet embedded at the bottom of an HTML file: var savedValues = [] var currentId = document.getElementById("fridgeFreezer").value function handleChange() { // Logic to handle user input changes: var temp = document.ge ...

Guide for setting up multiple checkbox event listeners with jQuery

I currently have 2 checkboxes on my form: <form action=""> <input id="bikeCheckbox" type="checkbox" name="bikeCheckbox" value="Bike">I own a bike<br> <input id="carCheckbox" type="checkbox" name="carCheckbox" value="Car">I ...

Automatically identify the appropriate data type using a type hint mechanism

Can data be interpreted differently based on a 'type-field'? I am currently loading data from the same file with known type definitions. The current approach displays all fields, but I would like to automatically determine which type is applicab ...