Vinit Desai
Vinit Desai

Reputation: 520

Line chart customization using D3.js and AngularJS

I am developing a line chart using D3.js library and AngularJS in Ionic. I want to customize the colour of data point depending on the value of Y-axis. Say, the value is in range 0-30 show the data point in green colour, the value is in range 31-40 show the data point in yellow colour, the value is in range 41-60 show the data point in red colour etc. I am using D3 for the first time. Also, In my code I'll be fetching data dynamically(to be specific) from back-end json file. At the back-end, there is a parameter named e(dependent on data value of Y-axis) which ranges from 0 to 3 and accordingly colour code is set at front-end depending on the which value e has. Also, the e parameter will wary for different scenarios of Y axis(Sales, Tax). For sales, 0 means 110-150, but for Tax, 0 means 50-90.Can anyone help me with this? Expected line chart image

Upvotes: 0

Views: 575

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

You can try something like this to color the circle nodes for the y axis values (In my example below its data close):

svg.selectAll("dot")
    .data(data)
    .enter().append("circle")
    .attr("r", 3.5)
    .style("fill", function(d){
       if (d.close < 100)
           return "red";
       if (d.close < 200)
           return "brown";
       if (d.close < 300)
           return "green";
       if (d.close < 400)
           return "blue";
       if (d.close < 500)
           return "yellow" ;  
       if (d.close < 600)
           return "pink" ;       
       if (d.close < 700)
           return "orange" ;  
    })

For angular you need to make this as directive...

EDIT I have added a div for showing tooltip like below

<div id="mytooltip" style="position: absolute; z-index: 10; visibility: hidden; top: 82px; left: 81px;">
    <div id="ttclose"></div>
    <div id="ttdate"></div>
</div>

Then on move event you can show and set values as below:

.on("mouseover", function () {
                return d3.select("#mytooltip").style("visibility", "visible"); //making the tooltip visible
            })
                .on("mousemove", function (d) {
                console.log()
                d3.select("#mytooltip").style("top", (d3.mouse(this)[1] + 10) + "px").style("left", (d3.mouse(this)[0] + 10) + "px");
                d3.select("#mytooltip").select("#ttdate").text(function () {
                    return d.date; //setting the date values to tooltip
                });
                d3.select("#mytooltip").select("#ttclose").text(function () {
                    return d.close; //setting the date values to tooltip
                });
                return;
            })
                .on("mouseout", function () {
                return d3.select("#mytooltip").style("visibility", "hidden"); //hidding the tooltip
            });

Full working code here

Hope this helps!

Upvotes: 1

Related Questions