Time in x-axis and data for the y-axis for line chart in d3.js doesn't match/show with what (data) is on JSON

Elijah Leis

$(document).ready(() => {
    // set the dimensions and margins of the graph
    var margin = { top: 20, right: 20, bottom: 30, left: 50 },
        width = 960 - margin.left - margin.right,
        height = 500 - margin.top - margin.bottom;

    // parse the date / time
    var parseTime = d3.timeParse("%H:%M:%S");


    // set the ranges
    var x = d3.scaleTime().range([0, width]);
    var y = d3.scaleLinear().range([height, 0]);

    // define the line
    var valueline = d3.line()
        .x(function (d) { return x(d.availability_time); })
        .y(function (d) { return y(d.total_hour_percentage); });

    // append the svg obgect to the body of the page
    // appends a 'group' element to 'svg'
    // moves the 'group' element to the top left margin
    var svg = d3.select("#lineChart").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 + ")");

    function draw(data) {
        console.log(data[0].availability_time);

        // format the data
        data.forEach(function (d) {
            d.availability_time = (parseTime(d.availability_time));
            d.total_hour_percentage = d.total_hour_percentage;
        });

        // sort time ascending
        data.sort(function (a, b) {
            return a["availability_time"] - b["availability_time"];
        })

        // Scale the range of the data
        x.domain(d3.extent(data, function (d) {
            return d.availability_time;
        }));
        y.domain([0, d3.max(data, function (d) {
            return Math.max(d.total_up_percentage);
        })]);

        // Add the valueline path.
        svg.append("path")
            .data([data])
            .attr("class", "line")
            .attr("d", valueline);
        // Add the X Axis
        svg.append("g")
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x));

        // Add the Y Axis
        svg.append("g")
            .call(d3.axisLeft(y));
    }
    // Get the data
    // var perHourResult = "/perHourAvailabilities/" + defaultDate;
    // console.log(perHourResult);

    var perHourResult = 
    [
        {"id":0,"availability_time":"00:00:00","total_hour_percentage":99.55},
        {"id":0,"availability_time":"01:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"02:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"03:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"04:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"05:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"06:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"07:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"08:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"09:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"10:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"11:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"12:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"13:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"14:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"15:00:00","total_hour_percentage":99.75},
        {"id":0,"availability_time":"16:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"17:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"18:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"19:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"20:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"21:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"22:00:00","total_hour_percentage":100.0},
        {"id":0,"availability_time":"23:00:00","total_hour_percentage":100.0}
    ];

    console.log(perHourResult[0].availability_time);

    draw(perHourResult);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.5.0/d3.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DASHBOARD</title>

    <!--Lib css-->
    <!--bootstrap-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
        integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <!--fontawesome-->
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"
        integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
    <!--own css-->
    <style>
        @import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";

        body {
            font-family: 'Poppins', sans-serif;
            background: #fafafa;
        }

        p {
            font-family: 'Poppins', sans-serif;
            font-size: 1.1em;
            font-weight: 300;
            line-height: 1.7em;
            color: #999;
        }

        a,
        a:hover,
        a:focus {
            color: inherit;
            text-decoration: none;
            transition: all 0.3s;
        }

        .navbar {
            padding: 15px 10px;
            background: #fff;
            border: none;
            border-radius: 0;
            margin-bottom: 40px;
            box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
        }

        .navbar-btn {
            box-shadow: none;
            outline: none !important;
            border: none;
        }


        /* ---------------------------------------------------
    SIDEBAR STYLE
----------------------------------------------------- */

        .wrapper {
            display: flex;
            width: 100%;
            align-items: stretch;
        }

        #sidebar {
            min-width: 250px;
            max-width: 250px;
            background: rgb(60, 95, 238);
            color: #fff;
            transition: all 0.3s;
        }

        #sidebar.active {
            margin-left: -250px;
        }

        #sidebar .sidebar-header {
            padding: 20px;
            background: rgb(90, 121, 243);
        }

        #sidebar ul.components {
            padding: 20px 0;
            border-bottom: 1px solid #47748b;
        }

        #sidebar ul p {
            color: #fff;
            padding: 10px;
        }

        #sidebar ul li a {
            padding: 10px;
            font-size: 1.1em;
            display: block;
        }

        #sidebar ul li a:hover {
            color: #7386D5;
            background: #fff;
        }

        #sidebar ul li.active>a,
        a[aria-expanded="true"] {
            color: #fff;
            background: #6d7fcc;
        }

        a[data-toggle="collapse"] {
            position: relative;
        }

        .dropdown-toggle::after {
            display: block;
            position: absolute;
            top: 50%;
            right: 20px;
            transform: translateY(-50%);
        }

        ul ul a {
            font-size: 0.9em !important;
            padding-left: 30px !important;
            background: #6d7fcc;
        }

        ul.CTAs {
            padding: 20px;
        }

        ul.CTAs a {
            text-align: center;
            font-size: 0.9em !important;
            display: block;
            border-radius: 5px;
            margin-bottom: 5px;
        }

        a.download {
            background: #fff;
            color: #7386D5;
        }

        a.article,
        a.article:hover {
            background: #6d7fcc !important;
            color: #fff !important;
        }

        /* ---------------------------------------------------
    CONTENT STYLE
----------------------------------------------------- */

        #content {
            width: 100%;
            padding: 20px;
            min-height: 100vh;
            transition: all 0.3s;
        }

        /* ---------------------------------------------------
    MEDIAQUERIES
----------------------------------------------------- */

        @media (max-width: 768px) {
            #sidebar {
                margin-left: -250px;
            }

            #sidebar.active {
                margin-left: 0;
            }

            #sidebarCollapse span {
                display: none;
            }
        }

        /* ---------------------------------------------------
    CHART STYLE
----------------------------------------------------- 

.mb-4,
.my-4 {
  margin-bottom: 1.5rem !important;
}

.pt-3,
.py-3 {
  padding-top: 1rem !important;
}

.pb-3,
.py-3 {
  padding-bottom: 1rem !important;
}   */

        #bar-chart {
            min-height: 37rem;
        }

        #bar-chart svg {
            overflow: visible;
        }

        body {
            font-family: 'Open Sans', sans-serif;
        }

        div#layout {
            text-align: center;
        }

        div#bar-chart {
            width: 1000px;
            height: 600px;
            margin: auto;

        }

        svg {
            width: 100%;
            height: 100%;
        }

        .bar {
            fill: #80cbc4;
        }

        text {
            font-size: 12px;
            fill: rgb(12, 1, 1);
        }

        path {
            stroke: gray;
        }

        line {
            stroke: gray;
        }

        line#limit {
            stroke: #FED966;
            stroke-width: 3;
            stroke-dasharray: 3 6;
        }

        .grid path {
            stroke-width: 0;
        }

        .grid .tick line {
            stroke: #9FAAAE;
            stroke-opacity: 0.3;
        }

        text.divergence {
            font-size: 14px;
            fill: #2F4A6D;
        }

        text.value {
            font-size: 14px;
        }

        text.title {
            font-size: 22px;
            font-weight: 600;
        }

        text.label {
            font-size: 14px;
            font-weight: 400;
        }

        text.source {
            font-size: 10px;
        }

        #pieChart {
            min-height: 18rem;
        }

        #pieChart svg {
            overflow: visible;
        }

        .content-header {
            padding-bottom: 2em;
        }

        /* LINE CHART STYLE */

        .axis--x path {
            display: none;
        }

        .line {
            fill: none;
            stroke: steelblue;
            stroke-width: 1.5px;
        }
    </style>

    <!--lib js-->
    <!--jquery-->
    <script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
    <!--bootstrap-->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
        integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
        crossorigin="anonymous"></script>

    <!--fontawesome js-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/all.min.js"></script>

    <!--d3(chart) js-->
    <script src="https://d3js.org/d3.v5.min.js"></script>

</head>

<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <nav id="sidebar">
            <ul class="list-unstyled components">
                <li class="active">
                    <a href="/">DASHBOARD</a>
                </li>
            </ul>
            <!--End of nav.sidebar-->
        </nav>

        <!--Page content-->
        <div id="content">
            <!-- navbar -->
            <nav class="navbar navbar-expand-lg navbar-light bg-light">
                <div class="container-fluid">
                    <button type="button" id="sidebarCollapse" class="btn btn-info">
                        <i class="fas fa-align-justify"></i>
                    </button>
                </div>
            </nav>

            <!--End of div.row-->
            <div class="row">
                <div class="col-12">
                    <div class="card shadow mb-5">
                        <div class="card-body">
                            <div id="lineChart">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!--End of div.row-->
        </div>


    </div>
    <!--End of div.content-->

    </div>
    <!--End of div.wrapper-->

    <!--Lib <script>-->


    <!--own <script>-->

    <script src="js/script3.js"></script>


</body>

</html>

Time in the x-axis of my line chart doesn't show the interval of 00:00:00 to 23:00:00. It just shows the 3am, 9am, 12pm, 3pm, 6pm, and 9pm like in the picture below: 3

Data also won't show on the y-axis. I was expecting that it will show 0,10,20...100.

Below is the code for my line chart.

$(document).ready(() => {
// set the dimensions and margins of the graph
var margin = { top: 20, right: 20, bottom: 30, left: 50 },
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

// parse the date / time
var parseTime = d3.timeParse("%Y");

// set the ranges
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);

// define the line
var valueline = d3.line()
    .x(function (d) { return x(d.Date); })
    .y(function (d) { return y(d.Imports); });
// define the line
var valueline2 = d3.line()
    .x(function (d) { return x(d.Date); })
    .y(function (d) { return y(d.Exports); });

// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("#lineChart").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 + ")");

function draw(data) {
    console.log(data);

    // format the data
    data.forEach(function (d) {
        d.Date = parseTime(d.Date);
        d.Imports = +d.Imports;
        d.Exports = +d.Exports;
    });

    // sort years ascending
    data.sort(function (a, b) {
        return a["Date"] - b["Date"];
    })

    // Scale the range of the data
    x.domain(d3.extent(data, function (d) { 
        return d.Date; 
    }));
    y.domain([0, d3.max(data, function (d) {
        return Math.max(d.Imports, d.Exports);
    })]);

    // Add the valueline path.
    svg.append("path")
        .data([data])
        .attr("class", "line")
        .attr("d", valueline);
    // Add the valueline path.
    svg.append("path")
        .data([data])
        .attr("class", "line")
        .attr("d", valueline2);
    // Add the X Axis
    svg.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));

    // Add the Y Axis
    svg.append("g")
        .call(d3.axisLeft(y));
}
// Get the data

d3.json("data.json")
    .then((data) => {
       // console.log(data.length);

        //console.log(data[0].Date)
            d3.select("#selectButton")
                .selectAll("myOptions")
                .data(data)
                .enter()
                .append("option")
                .text((d) => {
                    return d.Date;
                })
                .attr("value", (d) => {
                    return d.Date;
                })
            //console.log(data[i].Date);

        draw(data);
    })
    .catch((error) => {
        console.log(error);
    });
});

Don't mind the comments. I've put them there so i can ensure that the data is being passed on in every level and as you can see on the JSON data below every data is being passed correctly: enter image description here

I've tried everything I could fine on the internet but nothing can fixed it. Hopefully someone can help me. Big thanks in advance!

Pablo EM

Here you have a MWE of the fixed chart: https://jsfiddle.net/26kqjwsb/

Some things to take into account.

  • You are using total_up_percentage in the y domain definition:

    y.domain([0, d3.max(data, function (d) { return Math.max(d.total_up_percentage); })]);

    But the field name should be total_hour_percentage.

  • Your y values are between 99.55 and 100. If the y axis is between 0 and 100, you'll see only a plain line.

  • D3js by default generates filled paths, so you must set your path fill and stroke properties to plot a line chart.

  • The dates in the x-axis are the expected according to your dataset.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

D3 Bar chart. How to set custom x and y axis based on JSON data?

Line-chart of time-series data with monthly labels on x-axis but daily data on y-axis

Dual Y axis line chart in d3.js without external data

d3 multi line alignment with y axis data

chart.js 3 and time axis displays wrong date data

Data point in Chart js line chart not positioned along y axis correctly when retrieve data from firestore

D3.js - Plotting time series data - Format x-axis from JSON

How to put data on line chart when x axis and data has a time range

chart data on 24hr X axis using recharts, chart.js, I don't mind what

How to specify x-axis and y-axis input data in dc.js time series graph?

Chart js - Chart doesn't show when x axis has type 'time'

D3 x Axis data is overlaping

XY Scatter Chart with Smooth Line doesn't consider Time in DateTime X-Axis

Adding a y axis horizonal line to a D3 scatter chart

How to hide the y axis and x axis line and label in my bar chart for chart.js

Line Chart (Dual-Y) x-axis data in reverse order

x axis rescale using dropdown in line chart d3

Scaling y-axis appropriate to data in multiple line chart display

Why does putting two data sets with a Time Cartesian axis in Chart.js cause two Y axis tick sets?

Google Line chart with dual Y axis but with 3 or more time series

Position of the x-axis labels is not in sync with the line chart data points

Creating a line chart with monthly data unerneath the x axis

How to display second y-axis to right of grouped bar chart data in d3

Excel chart: How to reverse the X axis of time series data

Scatter Chart: Data isn't populating correctly (X/Y Axis all zeros?)

chart.js: hide specific ticks in y-axis and hide all x-axis grid line

Multiple Y-Axis Google chart with Json data

Chart.js Y-Axis data not rendering

Multiple y-axis using chart js with data as a dictionnary