61512

how to display data from 1st point on words on y axis for line chart in d3.js

<img src=https://www.e-learn.cn/content/wangluowenzhang/"https://i.stack.imgur.com/itna9.png" alt="enter image description here">

As shown in the above image, line chart taking some gap between y axis and data. graph and date should start from intersection point of the chart. 1st date should display at intersection point(as 0 starts in y-axis) How to remove the gap between intersection point and 1st date in d3.js(v3 version).

I am unable to find the proper axis, please help me to come out of this.. here is my code

<strong>index.html</strong> <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
    background-color: #F1F3F3
}

.axis {
    font: 10px sans-serif;
}

.bar1 {

        font-size: 12px;
        color: black;
    }
.axis path,
.axis line {
    fill: none;
    stroke: black;
    stroke-width: 1px;
    shape-rendering: crispEdges;
}


.line {
    fill: none;


    /* stroke-width: 2px;*/
}

.line1 {
    fill: none;
}

.overlay {
    fill: none;
    pointer-events: all;
}

.area1 {
    fill: steelblue;
}
.legend {
    border: 2px solid;
}
svg {
    border: 2px solid;
    margin-left: 90px;
    margin-top: 30px;
}
</style>

<body>
    <div id="lineChart"></div>
    <script src="https://d3js.org/d3.v3.min.js"></script>
    <script>
    var data = [{
            "year": "01/01/2005 00:01",
            "value": 700,
            "value1": 1000
        },
        {
            "year": "01/02/2005 00:02",
            "value": 625,
            "value1": 1000
        },
        {
            "year": "01/03/2005 00:03",
            "value": 852,
            "value1": 1000
        },
        {
            "year": "01/04/2005 00:04",
            "value": 888,
            "value1": 1000
        },
        {
            "year": "01/05/2005 00:05",
            "value": 689,
            "value1": 1000
        },
        {
            "year": "01/06/2005 00:06",
            "value": 772,
            "value1": 1000
        },
        {
            "year": "01/07/2005 00:07",
            "value": 700,
            "value1": 1000
        },
        {
            "year": "01/08/2005 00:08",
            "value": 776,
            "value1": 1000
        },
        {
            "year": "01/09/2005 00:09",
            "value": 650,
            "value1": 1000
        },
        {
            "year": "01/10/2005 00:10",
            "value": 779,
            "value1": 1000
        },
        {
            "year": "01/11/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/12/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/13/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/13/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/14/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/15/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/16/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/17/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/18/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/19/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/20/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/21/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/22/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/23/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/24/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/25/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/26/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/27/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/28/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/29/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/30/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/31/2005 00:11",
            "value": 600,
            "value1": 1000
        }
    ];
    var margin = { top: 20, right: 20, bottom: 100, left: 30 },
        width = 600 - margin.left - margin.right,
        height = 300 - margin.top - margin.bottom;

    var color_hash = [{
            "text": " Maximum Value",
            "color": "steelblue"
        },
        {
            "text": "Consumed Value",
            "color": "yellow"
        },
    ];

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



    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .tickFormat(function(d) {
            return d3.time.format('%m/%d/%Y')(new Date(d));
        });;


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

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


    var line = d3.svg.line()
        .interpolate("cardinal")
        .x(function(d) { return x(d.year); })
        .y(function(d) { return y(d.value); });

    var line1 = d3.svg.line()
        .interpolate("cardinal")
        .x(function(d) { return x(d.year); })
        .y(function(d) { return y(d.value1); });



    var area = d3.svg.area()
        .interpolate("cardinal")
        .x(function(d) { return x(d.year); })
        .y0(height)
        .y1(function(d) { return y(d.value); });

    var area1 = d3.svg.area()
        .interpolate("cardinal")
        .x(function(d) { return x(d.year); })
        .y0(height)
        .y1(function(d) { return y(d.value1); });


    var g = svg.append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");



    data.forEach(function(d) {
        d.year = d.year;
        d.value = +d.value;
        d.value1 = +d.value1;
    });

    x.domain(data.map(function(d) { return d.year; }));
    y.domain([0, d3.max(data, function(d) { return d.value, d.value1 + 100; })]);

    g.append("g")
        .attr("class", "axis axis--x")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)
        .selectAll("text")
        .style("text-anchor", "end")
        .attr("dx", "-.9em")
        .attr("dy", "-.6em")
        .attr("transform", "rotate(-90)")
    svg.append("text")
        .attr("transform", "translate(" + (width / 2) + " ," + (height + margin.top + 80) + ")")
        .style("text-anchor", "middle")
        .text("Year");;

    g.append("g")
        .attr("class", "axis axis--y")
        .call(yAxis)
    svg.append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", margin.left - 70)
        .attr("x", 0 - (height / 2) - 20)
        .attr("dy", "2em")
        .style("text-anchor", "middle")
        .text("Values");

    g.append("path")
        .datum(data)
        .attr("class", "line")
        .attr("d", line)
        .attr("stroke", "red")
        .attr("stroke-width", "1");

    g.append("path")
        .datum(data)
        .attr("class", "line1")
        .attr("d", line1)
        .attr("stroke", "red")
        .attr("stroke-width", "1");

    g.append("path")
        .data([data])
        .attr("class", "area")
        .attr("d", area)
        .style("fill", "steelblue")
        .attr("opacity", 1);

    g.append("path")
        .data([data])
        .attr("class", "area1")
        .attr("d", area1)
        .style("fill", "steelblue")
        .attr("opacity", .5);

    svg.append("text")
        .attr("x", (width / 2) + 20)
        .attr("y", 20 - (margin.top / 2))
        .attr("text-anchor", "middle")
        .style("font-size", "16px")

        .text("Day Wise Power Consumption");


    var legend = d3.select('svg').append('g')
        .attr("class", "legend")

    legend.selectAll('g')
        .data(color_hash) //hard coding the labels as the datset may have or may not have but legend should be complete.
        .enter().append("g")
        .attr("transform", function(d, i) { return "translate(0," + i * 25 + ")"; })
        .each(function(d, i) {
        var g = d3.select(this);
        g.append("rect")
            .attr("x", width - 300)
            .attr("y", 320)
            .attr("width", 18)
            .attr("height", 18)
            .attr("opacity", 0.7)
            .style("fill", function(d) { 
                return d.color 
            });

        // draw legend text
        g.append("text")
            .attr("x", width - 165)
            .attr("y", 327)
            .attr("dy", ".35em")
            .style("text-anchor", "end")
            .text(function(d) { 
                return d.text; 
            });
    });
   

    g.selectAll("dot")
        .data(data)
        .enter().append("circle")
        .attr("r", 3)
        .attr("fill", "black")
        .attr("cx", function(d) { return x(d.year); })
        .attr("cy", function(d) { return y(d.value); });

    g.selectAll("dot")
        .data(data)
        .enter().append("circle")
        .attr("r", 3)
        .attr("fill", "black")
        .attr("cx", function(d) { return x(d.year); })
        .attr("cy", function(d) { return y(d.value1); });
    </script>
</body>

</html>


Answer1:

I made a few small changes, but they were all around the way the xscale was created. d3 v3 has a d3.time.scale() which is great for this sort of thing. So I switched your x scale to that, and parsed your year values into date objects. I also added .nice() to your xscale domain creation which help to add starting and ending ticks.

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
    background-color: #F1F3F3
}

.axis {
    font: 10px sans-serif;
}

.bar1 {

        font-size: 12px;
        color: black;
    }
.axis path,
.axis line {
    fill: none;
    stroke: black;
    stroke-width: 1px;
    shape-rendering: crispEdges;
}


.line {
    fill: none;


    /* stroke-width: 2px;*/
}

.line1 {
    fill: none;
}

.overlay {
    fill: none;
    pointer-events: all;
}

.area1 {
    fill: steelblue;
}
.legend {
    border: 2px solid;
}
svg {
    border: 2px solid;
    margin-left: 90px;
    margin-top: 30px;
}
</style>

<body>
    <div id="lineChart"></div>
    <script src="https://d3js.org/d3.v3.min.js"></script>
    <script>
    var data = [{
            "year": "01/01/2005 00:01",
            "value": 700,
            "value1": 1000
        },
        {
            "year": "01/02/2005 00:02",
            "value": 625,
            "value1": 1000
        },
        {
            "year": "01/03/2005 00:03",
            "value": 852,
            "value1": 1000
        },
        {
            "year": "01/04/2005 00:04",
            "value": 888,
            "value1": 1000
        },
        {
            "year": "01/05/2005 00:05",
            "value": 689,
            "value1": 1000
        },
        {
            "year": "01/06/2005 00:06",
            "value": 772,
            "value1": 1000
        },
        {
            "year": "01/07/2005 00:07",
            "value": 700,
            "value1": 1000
        },
        {
            "year": "01/08/2005 00:08",
            "value": 776,
            "value1": 1000
        },
        {
            "year": "01/09/2005 00:09",
            "value": 650,
            "value1": 1000
        },
        {
            "year": "01/10/2005 00:10",
            "value": 779,
            "value1": 1000
        },
        {
            "year": "01/11/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/12/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/13/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/13/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/14/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/15/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/16/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/17/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/18/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/19/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/20/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/21/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/22/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/23/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/24/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/25/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/26/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/27/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/28/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/29/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/30/2005 00:11",
            "value": 600,
            "value1": 1000
        },
        {
            "year": "01/31/2005 00:11",
            "value": 600,
            "value1": 1000
        }
    ];
    var margin = { top: 20, right: 20, bottom: 100, left: 30 },
        width = 600 - margin.left - margin.right,
        height = 300 - margin.top - margin.bottom;

    var color_hash = [{
            "text": " Maximum Value",
            "color": "steelblue"
        },
        {
            "text": "Consumed Value",
            "color": "yellow"
        },
    ];

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



    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .tickFormat(function(d) {
            return d3.time.format('%m/%d/%Y')(new Date(d));
        });


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

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


    var line = d3.svg.line()
        .interpolate("cardinal")
        .x(function(d) { return x(d.year); })
        .y(function(d) { return y(d.value); });

    var line1 = d3.svg.line()
        .interpolate("cardinal")
        .x(function(d) { return x(d.year); })
        .y(function(d) { return y(d.value1); });



    var area = d3.svg.area()
        .interpolate("cardinal")
        .x(function(d) { return x(d.year); })
        .y0(height)
        .y1(function(d) { return y(d.value); });

    var area1 = d3.svg.area()
        .interpolate("cardinal")
        .x(function(d) { return x(d.year); })
        .y0(height)
        .y1(function(d) { return y(d.value1); });


    var g = svg.append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var timeFormat = d3.time.format("%m/%d/%Y %H:%M")

    data.forEach(function(d) {
        d.year = timeFormat.parse(d.year);
        d.value = +d.value;
        d.value1 = +d.value1;
    });

    x.domain([d3.min(data, function(d){return +d.year}), d3.max(data, function(d){return +d.year})]).nice();
    y.domain([0, d3.max(data, function(d) { return d.value, d.value1 + 100; })]);

    g.append("g")
        .attr("class", "axis axis--x")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)
        .selectAll("text")
        .style("text-anchor", "end")
        .attr("dx", "-.9em")
        .attr("dy", "-.6em")
        .attr("transform", "rotate(-90)")
    svg.append("text")
        .attr("transform", "translate(" + (width / 2) + " ," + (height + margin.top + 80) + ")")
        .style("text-anchor", "middle")
        .text("Year");;

    g.append("g")
        .attr("class", "axis axis--y")
        .call(yAxis)
    svg.append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", margin.left - 70)
        .attr("x", 0 - (height / 2) - 20)
        .attr("dy", "2em")
        .style("text-anchor", "middle")
        .text("Values");

    g.append("path")
        .datum(data)
        .attr("class", "line")
        .attr("d", line)
        .attr("stroke", "red")
        .attr("stroke-width", "1");

    g.append("path")
        .datum(data)
        .attr("class", "line1")
        .attr("d", line1)
        .attr("stroke", "red")
        .attr("stroke-width", "1");

    g.append("path")
        .data([data])
        .attr("class", "area")
        .attr("d", area)
        .style("fill", "steelblue")
        .attr("opacity", 1);

    g.append("path")
        .data([data])
        .attr("class", "area1")
        .attr("d", area1)
        .style("fill", "steelblue")
        .attr("opacity", .5);

    svg.append("text")
        .attr("x", (width / 2) + 20)
        .attr("y", 20 - (margin.top / 2))
        .attr("text-anchor", "middle")
        .style("font-size", "16px")

        .text("Day Wise Power Consumption");


    var legend = d3.select('svg').append('g')
        .attr("class", "legend")

    legend.selectAll('g')
        .data(color_hash) //hard coding the labels as the datset may have or may not have but legend should be complete.
        .enter().append("g")
        .attr("transform", function(d, i) { return "translate(0," + i * 25 + ")"; })
        .each(function(d, i) {
        var g = d3.select(this);
        g.append("rect")
            .attr("x", width - 300)
            .attr("y", 320)
            .attr("width", 18)
            .attr("height", 18)
            .attr("opacity", 0.7)
            .style("fill", function(d) { 
                return d.color 
            });

        // draw legend text
        g.append("text")
            .attr("x", width - 165)
            .attr("y", 327)
            .attr("dy", ".35em")
            .style("text-anchor", "end")
            .text(function(d) { 
                return d.text; 
            });
    });
   

    g.selectAll("dot")
        .data(data)
        .enter().append("circle")
        .attr("r", 3)
        .attr("fill", "black")
        .attr("cx", function(d) { return x(d.year); })
        .attr("cy", function(d) { return y(d.value); });

    g.selectAll("dot")
        .data(data)
        .enter().append("circle")
        .attr("r", 3)
        .attr("fill", "black")
        .attr("cx", function(d) { return x(d.year); })
        .attr("cy", function(d) { return y(d.value1); });
    </script>
</body>

</html>


Here is a fiddle with nice being used slightly better. I passed d3.time.days into .nice(). The reason there is a tick on the far right is nice rounds the extents and the last data point is slightly over the day mark.

Recommend

  • Looping transition in D3 version 4 and 5
  • Uncaught TypeError: Cannot read property 'length' of undefined
  • How to find if the second hand of a clock lies in the larger area or smaller one [closed]
  • Tree not updating nodes position when adding a new sibling
  • How to parse JSON values to be fed to formcontrol?
  • Getting error on applying transition in d3
  • Adding a SetTimeout and transition to jQuery Show / Hide
  • jquery accordion - remember active area when clicking back from an external link
  • How to label x-axis with dates?
  • Legend control with two data frames of different x-scales and different geoms in ggplot2
  • Dynamic DropDownLists In MVC 4 Form
  • Fill SVG path with a background-image without knowing height&width
  • Creating interactive SVG maps for a web portal
  • Greek letters in legend in R
  • Jquery resizable reposition handle after scroll
  • Function JavaScript : on Menu CSS HTML
  • How can I add div content to a new page in jspdf?
  • Caret disappears when the background of a textbox is gray in wpf
  • d3.js selection conditional rendering
  • Select inner HTML item in CSS
  • How to add closing tag for canvas in three js rendered Canvas?
  • How to rotate the dial in a gauge chart? Using python plotly
  • cell spacing in div table
  • Cut the background to expose the layer below
  • Floated image with variable width and heading with background image
  • Can someone please explain to me in the most layman terms how to use EventArgs?
  • How to add a focus style to an editable ComboBox in WPF
  • Listbox within Listbox and scrolling trouble in Windows Phone 7 Silverlight
  • Row Count Is Returning the incorrect number using RaptureXML
  • Disable Enter in editText android
  • Change multiple background-images with jQuery
  • Algorithm for a smudge tool?
  • Repeat a vertical line on every page in Report Builder / SSRS
  • Change JButton Shape while respecting Look And Feel
  • Can Jackson SerializationFeature be overridden per field or class?
  • How to check if every primary key value is being referenced as foreign key in another table
  • WinForms: two way TextBox problem
  • jquery mobile loadPage not working
  • Android Studio and gradle
  • python regex in pyparsing