D3.js Bar Chart Code Example



The example directly below is the code I wrote to create a scatterplot chart for a dashboard




.barTwo {
    fill: navy
}

    .barTwo:hover {
        fill: lightblue
    }

.barThree {
    fill: darkred
}

    .barThree:hover {
        fill: lightgrey
    }

#slider {
    max-width: 80%;
    margin-left: 1%;
    margin-bottom: 1%;
    background-color: #c1ccde;
}

#sliderTwo {
    color: darkgrey;
    font-family: arial;
    font-size: 14px;
}

.toolTip {
    position: absolute;
    display: none;
    min-width: 80px;
    height: auto;
    background: none repeat scroll 0 0 azure;
    border: 1px solid navy;
    border-radius: 10px;
    font-family: Arial,Helvetica Neue,Helvetica;
    font-size: 12px;
    padding: 7px;
    text-align: center;
}

#button-container {
    display: inline-block;
    position: relative;
    width: 100%;
    
}

#play-button {
    margin: 1% 1% 1% 1%;
    -moz-transition: all .5s ease-in;
    -o-transition: all .5s ease-in;
    -webkit-transition: all .5s ease-in;
    transition: all .5s ease-in;
    background: #5068bf;
    border-radius: 6px;
    border: none;
    color: white;
    margin: 0;
    padding: 0 12px;
    width: 60px;
    cursor: pointer;
    height: 30px;
}

    #play-button:hover {
        background-color: #91b2c9;
    }


#reset-button {
    margin: 1% 1% 1% 1%;
    -moz-transition: all .5s ease-in;
    -o-transition: all .5s ease-in;
    -webkit-transition: all .5s ease-in;
    transition: all .5s ease-in;
    background: #5d5c78;
    border-radius: 6px;
    border: none;
    color: white;
    margin: 0;
    padding: 0 12px;
    width: 60px;
    cursor: pointer;
    height: 30px;
}

    #reset-button:hover {
        background-color: #8c8aab;
    }


#selectButton {
    margin: 1% 1% 1% 1%;
    background: #5d5c78;
    border-radius: 6px;
    border: none;
    color: white;
    margin: 0;
    padding: 0 12px;
    width: 60px;
    cursor: pointer;
    height: 30px;
}

#seconds {
    margin: 1% 1% 1% 1%;
    background: #5e79db;
    border-radius: 6px;
    border: none;
    color: white;
    margin: 0;
    padding: 0 12px;
    width: 130px;
    cursor: pointer;
    height: 30px;
}


var margin = {top: 30, right: 10, bottom: 30, left: 45},
width = 800 - margin.left - margin.right,
height = 350 - margin.top - margin.bottom;

var svg = d3.select("#MyChart").append("svg")
.attr('preserveAspectRatio', 'xMinYMin meet')
.attr(
'viewBox',
'0 0 ' +
(width + margin.left + margin.right) +
' ' +
(height + margin.top + margin.bottom)
)
//.style("border", "1px solid grey")
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");

//   var LegendTest = d3.select("body").append("svg")
// .attr("width", 200)
//     .attr("height", 200)
//   .style("border", "1px solid grey")
//  // .selectAll("g")



//  GLOBAL VARIABLES
// ==========================================================
var inter;
var nested;
var MySales;
var MyYear;
var selectedFruit = 0; // so it has default value
var i = -1;
var LegendTransitionTime = 1700;
var IntervalSecondDelay = 1000;

// Min Max Year Global Variables
var YearArray = [];
var YearIndex = [];
var MinYear;
var MaxYear;
var legend;
var tooltip = d3.select("body").append("div").attr("class", "toolTip");
//              INITIAL FUNCTION
//=======================================================================

GetMinMaxYears()

function GetMinMaxYears()
{

//old --> d3.json("https://api.myjson.com/bins/j8u3o").then(function (data){
d3.json("https://api.myjson.com/bins/16vp7e").then(function (data){

nested = d3.nest()
.key(function(d) {return d.Year})
.rollup( v =>
v.map( elem =>
    ({key: elem["Airline"], value: Number(elem["Sales"]) })
)
)
.entries(data);


let airlines = nested.filter( x => x.key === nested[1].key)[0].value;

var colorScale = d3.scaleOrdinal()
.domain(airlines.map(function(d, i){return i}))
.range(["#b3d1ff", "#80b3ff", "#4d94ff", "#0052cc", "#002966"])


legend = svg.append("svg")
// .attr("width",  2000)
//   .attr("height", 110)
.selectAll("g")
.data(airlines)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });


legend.append("circle")
.attr("cx", 5)
.attr("cy", 5)
.attr("r", 6)
.attr("transform", "translate(638, 4)")
.style("fill", function(d){ return colorScale(d.key)});

legend
.append("text")
.attr("transform", "translate(630, 0)")
.attr("x", 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("font-family", "Arial,Helvetica Neue,Helvetica")
.style("font-size", "10px")
.attr("fill", "#484848")
.text(function(d){return d.key})


YearArray.push("Choose A Year")

for(var i = 0; i < nested.length; i++)
{
YearArray.push(nested[i].key);
}




MinYear = Math.min.apply(Math, YearArray);
MaxYear = Math.max.apply(Math, YearArray);

for(var i = 0; i < YearArray.length; i++)
{
YearIndex.push(i);

}



var dropdown =  d3.select("#selectButton")

var options = dropdown
.selectAll('myOptions')
.data(YearArray)
.enter()
.append("option")
.attr("value", function(d) {
return d;
})
.text(function(d) {
return d;
});

options.property("selected", function(d){return d === "SELECT" });




// d3.select("#selectButton")
//        .selectAll('myOptions')
//        .data(YearArray)
//        .enter()
//        .append("option")
//        .text(function (d) { return d; })
//        .attr("value", function (i) { return i; })
//       .property("selected", function(d){return d === "Select A Value" })
//       // .attr("value", function (d, i) { return i; })





d3.select('#selectButton').on('change', function(d, i) {
// Change the current key and call the function to update the colors.
// subtracted one from the index because the default "select" value pushes it up from 0 to 1
selectedFruit = this.options[this.selectedIndex].index - 1;

let airlines = nested.filter(x => x.key === nested[selectedFruit].key)[0].value;

//      document.getElementById("sliderTwo").innerHTML = "Current Year " +
// ""+  nested[selectedFruit].key +  ""

MySelectBox(airlines)
})


});

}


d3.json("https://api.myjson.com/bins/16vp7e").then(function (data){


nested = d3.nest()
.key(function(d) {return d.Year})
.rollup( v =>
v.map( elem =>
    ({key: elem["Airline"], value: Number(elem["Sales"])  })
)
)
.entries(data);

// ADD INDEX HERE
let airlines = nested.filter( x => x.key === nested[0].key)[0].value;


$("#slider" ).slider({
min: MinYear,
max: MaxYear,
step: 1,
// values: d3.extent(data.map(function(d){return d.Sales})),
slide: function(event, ui){
var index = $(ui.handle).index();
YearSelected = ui.value;

for(var i = 0; i < YearIndex.length; i++)
{
switch(true)
{
case YearSelected == nested[i].key:

var SwitchData = nested.filter( x => x.key === nested[i].key)[0].value;
MySlider(SwitchData)
break;

}
}
d3.select("#slider-data")
.html(YearSelected)}
});




var x = d3.scaleBand()
.domain(airlines.map(function(d){return d.key}))
.rangeRound([0, width]).padding(0.4);

svg.append("g")
.attr("class", "x axis")
.transition().duration(100)
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).scale(x));

svg.selectAll("g.x")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.transition().duration(1250)
.call(d3.axisBottom(x).scale(x));


var y = d3.scaleLinear()
.domain([0, d3.max(airlines.map(function(d){return d.value}))])
.range([height, 0]);

svg.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(y).scale(y));

svg.selectAll("g.y")
.transition().duration(2000)
.call(d3.axisLeft(y).scale(y).ticks(5));


//         var rects = svg.append("path")

//       .data([airlines]);

//     // define the line
// var valueline = d3.line()
//      .x(function(d) { return x(d.key); })
//      .y(function(d) { return y(+d.value); })


//   rects
//       .attr("fill", "none")
//       .attr("stroke", "navy")
//       .attr("stroke-width", 1.5)
//       .attr("d", valueline);


// var rects =  svg.selectAll("rect")
//       .data(airlines);

//    var colorScale = d3.scaleOrdinal()
//      .domain(airlines.map(function(d, i){return i}))
//     .range(["#b3d1ff", "#80b3ff", "#4d94ff", "#0052cc", "#002966"])

//     // Update old ones, already have x / width from before
//     rects
//     .enter()
//     .append("rect")
//      .style("fill", function(d){ return colorScale(d.key)})
//   .attr("x", function(d) { return x(d.key); })
//       .attr("y", function(d) { return y( +d.value); })
//        .attr("width", x.bandwidth())
//   .style("stroke", function(d, i){return colorScale(i)})
//       .attr("height", function(d) { return height - y(+d.value); })
//                 .on("mousemove", function(d){
//             tooltip
//               .style("left", d3.event.pageX - 50 + "px")
//               .style("top", d3.event.pageY - 70 + "px")
//               .style("display", "inline-block")
//               .html((d.key) + "
" + "$" + (d.value)); // }) // .on("mouseout", function(d){ tooltip.style("display", "none");}); $("#play-button") .on("click", function() { var button = $(this); if (button.text() == "Play") { button.text("Pause"); IntervalSecondDelay = $("#seconds").val(); inter = setInterval(function() { MyTimer(airlines); }, IntervalSecondDelay); } else { button.text("Play"); clearInterval(inter); } }) $("#reset-button") .on("click", function(){ // YearSelected = MinYear; data0 = nested.filter( x => x.key === nested[0].key)[0].value; MySelectBox(data0); })}); //========================================= // Timer Function function MyTimer(data) { i++; let airlines2 = nested[i] if (typeof(airlines2) != "undefined") { let airlines = nested.filter( x => x.key === nested[i].key)[0].value var colorScale = d3.scaleOrdinal() .domain(data.map(function(d, i){return i})) .range(["#b3d1ff", "#80b3ff", "#4d94ff", "#0052cc", "#002966"]) var ArrayOne = []; Object.keys(data).forEach(function(key) { ArrayOne.push(data[key].key); }) // d3.select("g").selectAll("text").remove(); // legend // .data(airlines) // .append("text") // .attr("transform", "translate(630, 0)") // .attr("x", 24) // .attr("y", 9) // .attr("dy", ".35em") // .style("font-family", "Arial,Helvetica Neue,Helvetica") // .style("font-size", "10px") // .attr("fill", "#484848") // .text(function(d){return d.key}) // d3.select("g").selectAll("circle").remove(); // legend.append("circle") // .data(airlines) // .style("fill", "azure") // .attr("cx", 5) // .attr("cy", 5) // .attr("r", 6) // .attr("transform", "translate(635, 4)") // .transition().duration(LegendTransitionTime) // .style("fill", function(d){ return colorScale(d.key)}); // d3.select(".OneClass") // .remove(); // var one = d3.select("svg").append("svg") // .attr("class", "OneClass"); // one // .append("text") // .attr("fill", "white") // //.attr("transform", "translate(745, 280)") // .attr("transform", "translate(699, 24)") // .text(nested[i].key) // .style("font-family", "Arial,Helvetica Neue,Helvetica") // .style("font-size", "10.5px") // .transition().duration(LegendTransitionTime) // .attr("fill", "#4d071f") // one // .append("circle") // .style("fill", "azure") // .attr("cx", 5) // .attr("cy", 5) // .attr("r", 6) // .attr("transform", "translate(680, 14)") // //.transition().duration(1000) // .style("fill", function(d){ return colorScale(d)}); // this.svg.selectAll(".PlayButtonLine").remove() //this.svg.selectAll(".PlayButtonLine").remove() var AirlineArray = []; var PriceArray = []; var CurrentYearArray = []; nested[i].value.map(function(d){return AirlineArray.push(d.key)}); nested[i].value.map(function(d){return PriceArray.push(d.value)}); //nested[i].value.map(function(d){return CurrentYearArray.push(d.key)}); //CurrentYearArray.push(nested[i].key); var xy = []; // start empty, add each element one at a time for(var a = 0; a < AirlineArray.length; a++ ) { xy.push({Airline: AirlineArray[a], Year: nested[i].key, Price: PriceArray[a]}); } console.log("xy is:", xy); // shows the data structure // document.getElementById("sliderTwo").innerHTML = "Current Year " + // ""+ nested[i].key +"" var x = d3.scaleBand() .domain(nested.map(function(d){return d.key})) .rangeRound([0, width]).padding(1.2); svg.append("g") .attr("class", "x axis") .transition().duration(100) .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x).scale(x)); svg.selectAll("g.x") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .transition().duration(2000) .call(d3.axisBottom(x).scale(x)); var y = d3.scaleLinear() .domain([0, d3.max(xy.map(function(d){return d.Price}))]) .range([height, 0]); svg.append("g") .attr("class", "y axis") .call(d3.axisLeft(y).scale(y)); svg.selectAll("g.y") .transition().duration(2000) .call(d3.axisLeft(y).scale(y).ticks(5)); var valueline = d3.line() .x(function(d) { return x(d.Year); }) .y(function(d) { return y(+d.Price); }) // // Add the valueline path. // svg.append("path") // .style("fill","none") // .style("stroke","navy") // .style("stroke-width","1.5px") // .attr("d", valueline(xy)) // Add the scatterplot var circle = svg.selectAll("dot") .data(xy) .enter().append("circle") .attr("id", function(d){ return d.Airline; }) .attr("class", "DOTS") .attr("r", 5.5) .style("fill", function(d, i){ return colorScale(i)}) .attr("stroke", "red") .attr("stroke-width", .5) .attr("fill", "none") .attr("cx", function(d) { return x(d.Year); }) .attr("cy", function(d) { return y(+d.Price); }) d3.selectAll("#MyChart") .attr("fill", "red") // var myClass = svg.selectAll("circle").attr("class"); // var cat = svg.selectAll("circle") // // .transition().duration(2500) // // .attr("r", 30) // .select(this).attr("id") // d3.selectAll("body").append("p").html("ID === " + JSON.stringify(d3.selectAll(".DOTS").attr("id"))) // d3.selectAll("body").append("p").html("X === " + JSON.stringify(svg.selectAll(".DOTS").attr("cx"))) // d3.selectAll("body").append("p").html("Y === " + JSON.stringify(svg.selectAll(".DOTS").attr("cy"))) var data1; var AirBalticDotCounter = -3; var AirBalticMinArray = []; var AirBalticMaxArray = []; svg.selectAll(".DOTS") // <-- A .each(function(d, i) { if(d3.select(this).attr("id") == "Air Baltic" ) { AirBalticDotCounter += 3; AirBalticMinArray.push( d3.select(this).attr("cx") ); AirBalticMaxArray.push( d3.select(this).attr("cy") ); // d3.selectAll("body").append("p").html("DotCount == " + DotCounter + " Index " + i ); // d3.selectAll("body").append("p").html("index == " + i ); // d3.selectAll("body").append("p").html(d3.select(this).attr("id")); // d3.selectAll("body").append("p").html(d3.select(this).attr("cx")); // d3.selectAll("body").append("p").html(d3.select(this).attr("cy")); } }); var AirItalyDotCounter = -1; var AirItalyMinArray = []; var AirItalyMaxArray = []; // WHITESPACE FOR AIR ITALY NAME ERROR svg.selectAll(".DOTS") // <-- A .each(function(d, i) { if(d3.select(this).attr("id") == "Air Italy " || d3.select(this).attr("id") == "Air Italy" ) { AirItalyDotCounter += 3; AirItalyMinArray.push( d3.select(this).attr("cx") ); AirItalyMaxArray.push( d3.select(this).attr("cy") ); // d3.selectAll("body").append("p").html("DotCount == " + AirItalyDotCounter + " Index " + i ); // d3.selectAll("body").append("p").html( AirItalyMaxArray[0] ); // d3.selectAll("body").append("p").html(d3.select(this).attr("id") + " - index -===>>>> " + i + " - Air Italy Dot Counter -===>>>> " + AirItalyDotCounter ); // d3.selectAll("body").append("p").html(d3.select(this).attr("cx")); // d3.selectAll("body").append("p").html(d3.select(this).attr("cy")); } }); var AirCanadaDotCounter = -2; var AirCanadaMinArray = []; var AirCanadaMaxArray = []; svg.selectAll(".DOTS") // <-- A .each(function(d, i) { if(d3.select(this).attr("id") == "Air Canada" ) { AirCanadaDotCounter += 3; AirCanadaMinArray.push( d3.select(this).attr("cx") ); AirCanadaMaxArray.push( d3.select(this).attr("cy") ); // d3.selectAll("body").append("p").html("DotCount == " + AirCanadaDotCounter ); // d3.selectAll("body").append("p").html(" Index " + i ); } }); // d3.selectAll("body").append("p").html(" Min == " + AirBalticMinArray[i] + " Max == " + AirBalticMaxArray[i] ); // d3.selectAll("body").append("p").html(" MinArray == " + Math.min(AirBalticMinArray[i]) + " MaxnArray == " + Math.min(AirBalticMaxArray[i]) ); // d3.selectAll("body").append("p").html("DotArray Is == " + Math.max(DotArray[i]) + " " + AirBalticMinArray[0] + " " + Math.max(AirBalticMinArray[i])); // for(var i = 0; i < DotArray.length; i++) // { // d3.selectAll("body").append("p").html("DotArray Is == " + DotArray[i] ); // } data1 = [{ //--------- Line One source: { x: AirBalticMaxArray[0], y: AirBalticMinArray[0] }, target: { x: AirBalticMaxArray[1], y: AirBalticMinArray[1] } }, //--------- Line Two { source: { x: AirBalticMaxArray[1], y: AirBalticMinArray[1] }, target: { x: AirBalticMaxArray[2], y: AirBalticMinArray[2] } } , //--------- Line Three { source: { x: AirBalticMaxArray[2], y: AirBalticMinArray[2] }, target: { x: AirBalticMaxArray[3], y: AirBalticMinArray[3] } } , //--------- Line Four { source: { x: AirBalticMaxArray[3], y: AirBalticMinArray[3] }, target: { x: AirBalticMaxArray[4], y: AirBalticMinArray[4] } } , //--------- Air Canada One { source: { x: AirCanadaMaxArray[0], y: AirCanadaMinArray[0] }, target: { x: AirCanadaMaxArray[1], y: AirCanadaMinArray[1] } } , //--------- Air Canada Two { source: { x: AirCanadaMaxArray[1], y: AirCanadaMinArray[1] }, target: { x: AirCanadaMaxArray[2], y: AirCanadaMinArray[2] } } , //--------- Air Canada Three { source: { x: AirCanadaMaxArray[2], y: AirCanadaMinArray[2] }, target: { x: AirCanadaMaxArray[3], y: AirCanadaMinArray[3] } } , //--------- Air Canada Four { source: { x: AirCanadaMaxArray[3], y: AirCanadaMinArray[3] }, target: { x: AirCanadaMaxArray[4], y: AirCanadaMinArray[4] } } , //--------- Air Italy Two { source: { x: AirItalyMaxArray[0], y: AirItalyMinArray[0] }, target: { x: AirItalyMaxArray[1], y: AirItalyMinArray[1] } } , //--------- Air Italy Three { source: { x: AirItalyMaxArray[1], y: AirItalyMinArray[1] }, target: { x: AirItalyMaxArray[2], y: AirItalyMinArray[2] } } , //--------- Air Italy Four { source: { x: AirItalyMaxArray[2], y: AirItalyMinArray[2] }, target: { x: AirItalyMaxArray[3], y: AirItalyMinArray[3] } } , //--------- Air Italy Four { source: { x: AirItalyMaxArray[3], y: AirItalyMinArray[3] }, target: { x: AirItalyMaxArray[4], y: AirItalyMinArray[4] } } , ]; // d3.select(".OneClass") // .remove(); // var one = d3.select("svg").append("svg") // .attr("class", "OneClass"); var link = d3.linkHorizontal() .x(function(d) { return d.y; }) .y(function(d) { return d.x; }); //d3.select(".TwoClass").remove(); d3.selectAll('.DOTS').on('click', function() { alert(d3.select(this).attr('id') + " " + d3.select(this).attr('cx') + " , " + d3.select(this).attr('cy') ); }); var x = d3.select('circle').datum(function() { return +d3.select(this).attr('cx') }); var y = d3.selectAll('circle').datum(function() { return +d3.select(this).attr('cy') }); var circleBox = circle.node().getBBox(); //Then, use those coordinates to set the x and y positions: // .attr("x", circleBox.x + circleBox.width/2 - widthMarker/2) // .attr("y",circleBox.y + circleBox.height/2 - widthMarker) // source: { // y: 0, // x: 167 // }, // target: { // y: 800, // x: 0 // } var Coordinates = []; Coordinates.push( { source: { y: circleBox.y, x: circleBox.x }, target: { y: circleBox.y, x: circleBox.x } , source: { y: circleBox.y, x: circleBox.x }, target: { y: circleBox.y, x: circleBox.x } }) // d3.select("body").append("p").html(" Data1 Is === === "+ JSON.stringify(data1)); // d3.select("body").append("p").html(" Data2 Is === === "+ JSON.stringify(Coordinates) ); // d3.select("body").append("p").html(" CircleBox.x === " + circleBox.x + " CircleBox.y " + JSON.stringify(circleBox)); svg.selectAll(null) // .attr("class", "TwoClass") //.data(Coordinates) .data(data1) .enter() .append("path") .attr("fill", "none") .attr("stroke", function(d, i){ return colorScale(i)}) .attr("stroke-width", "1.5px") .style("opacity", "4") .attr("d", link); // Usually you have a color scale in your chart already var data1 = ['red', 'blue', 'lightblue', 'grey', 'yellow']; } else if (typeof(airlines2) === "undefined") { // document.getElementById("sliderTwo").innerHTML = "Current Number " + i + // ""+ "End Of Series Reached" + new Date() + ""; clearInterval(inter); $(document).ready(function(){ // Change text of input button // $("#myInput").prop("value", "Input New Text"); // Change text of button element $("#play-button").html("Play"); // Here We Set The Counter To Zero i = 0; }); } } //========================================= // Select Box Function function MySelectBox(data) { var i = selectedFruit; let airlines = nested.filter( x => x.key === nested[i].key)[0].value var colorScale = d3.scaleOrdinal() .domain(data.map(function(d, i){return i})) .range(["#b3d1ff", "#80b3ff", "#4d94ff", "#0052cc", "#002966"]) var ArrayOne = []; Object.keys(data).forEach(function(key) { ArrayOne.push(data[key].key); }) // d3.select("g").selectAll("text").remove(); // legend // .data(airlines) // .append("text") // .attr("transform", "translate(630, 0)") // .attr("x", 24) // .attr("y", 9) // .attr("dy", ".35em") // .style("font-family", "Arial,Helvetica Neue,Helvetica") // .style("font-size", "10px") // .attr("fill", "#484848") // .text(function(d){return d.key}) // d3.select("g").selectAll("circle").remove(); // legend.append("circle") // .data(airlines) // .style("fill", "azure") // .attr("cx", 5) // .attr("cy", 5) // .attr("r", 6) // .attr("transform", "translate(635, 4)") // .transition().duration(LegendTransitionTime) // .style("fill", function(d){ return colorScale(d.key)}); // d3.select(".OneClass") // .remove(); // var one = d3.select("svg").append("svg") // .attr("class", "OneClass"); // one // .append("text") // .attr("fill", "white") // //.attr("transform", "translate(745, 280)") // .attr("transform", "translate(699, 24)") // .text(nested[i].key) // .style("font-family", "Arial,Helvetica Neue,Helvetica") // .style("font-size", "10.5px") // .transition().duration(LegendTransitionTime) // .attr("fill", "#4d071f") // one // .append("circle") // .style("fill", "azure") // .attr("cx", 5) // .attr("cy", 5) // .attr("r", 6) // .attr("transform", "translate(680, 14)") // //.transition().duration(1000) // .style("fill", function(d){ return colorScale(d)}); // this.svg.selectAll(".PlayButtonLine").remove() //this.svg.selectAll(".PlayButtonLine").remove() var AirlineArray = []; var PriceArray = []; var CurrentYearArray = []; nested[i].value.map(function(d){return AirlineArray.push(d.key)}); nested[i].value.map(function(d){return PriceArray.push(d.value)}); //nested[i].value.map(function(d){return CurrentYearArray.push(d.key)}); //CurrentYearArray.push(nested[i].key); var xy = []; // start empty, add each element one at a time for(var a = 0; a < AirlineArray.length; a++ ) { xy.push({Airline: AirlineArray[a], Year: nested[i].key, Price: PriceArray[a]}); } console.log("xy is:", xy); // shows the data structure // document.getElementById("sliderTwo").innerHTML = "Current Year " + // ""+ nested[i].key +"" var x = d3.scaleBand() .domain(nested.map(function(d){return d.key})) .rangeRound([0, width]).padding(1.2); svg.append("g") .attr("class", "x axis") .transition().duration(100) .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x).scale(x)); svg.selectAll("g.x") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .transition().duration(2000) .call(d3.axisBottom(x).scale(x)); var y = d3.scaleLinear() .domain([0, d3.max(xy.map(function(d){return d.Price}))]) .range([height, 0]); svg.append("g") .attr("class", "y axis") .call(d3.axisLeft(y).scale(y)); svg.selectAll("g.y") .transition().duration(2000) .call(d3.axisLeft(y).scale(y).ticks(5)); var valueline = d3.line() .x(function(d) { return x(d.Year); }) .y(function(d) { return y(+d.Price); }) // // Add the valueline path. // svg.append("path") // .style("fill","none") // .style("stroke","navy") // .style("stroke-width","1.5px") // .attr("d", valueline(xy)) // Add the scatterplot var circle = svg.selectAll("dot") .data(xy) .enter().append("circle") .attr("id", function(d){ return d.Airline; }) .attr("class", "DOTS") .attr("r", 5.5) .style("fill", function(d, i){ return colorScale(i)}) .attr("stroke", "orange") .attr("stroke-width", .5) .attr("fill", "none") .attr("cx", function(d) { return x(d.Year); }) .attr("cy", function(d) { return y(+d.Price); }) d3.selectAll("#MyChart") .attr("fill", "red") // var myClass = svg.selectAll("circle").attr("class"); // var cat = svg.selectAll("circle") // // .transition().duration(2500) // // .attr("r", 30) // .select(this).attr("id") // d3.selectAll("body").append("p").html("ID === " + JSON.stringify(d3.selectAll(".DOTS").attr("id"))) // d3.selectAll("body").append("p").html("X === " + JSON.stringify(svg.selectAll(".DOTS").attr("cx"))) // d3.selectAll("body").append("p").html("Y === " + JSON.stringify(svg.selectAll(".DOTS").attr("cy"))) var data1; var AirBalticDotCounter = -3; var AirBalticMinArray = []; var AirBalticMaxArray = []; svg.selectAll(".DOTS") // <-- A .each(function(d, i) { if(d3.select(this).attr("id") == "Air Baltic" ) { AirBalticDotCounter += 3; AirBalticMinArray.push( d3.select(this).attr("cx") ); AirBalticMaxArray.push( d3.select(this).attr("cy") ); // d3.selectAll("body").append("p").html("DotCount == " + DotCounter + " Index " + i ); // d3.selectAll("body").append("p").html("index == " + i ); // d3.selectAll("body").append("p").html(d3.select(this).attr("id")); // d3.selectAll("body").append("p").html(d3.select(this).attr("cx")); // d3.selectAll("body").append("p").html(d3.select(this).attr("cy")); } }); var AirItalyDotCounter = -1; var AirItalyMinArray = []; var AirItalyMaxArray = []; // WHITESPACE FOR AIR ITALY NAME ERROR svg.selectAll(".DOTS") // <-- A .each(function(d, i) { if(d3.select(this).attr("id") == "Air Italy " || d3.select(this).attr("id") == "Air Italy" ) { AirItalyDotCounter += 3; AirItalyMinArray.push( d3.select(this).attr("cx") ); AirItalyMaxArray.push( d3.select(this).attr("cy") ); // d3.selectAll("body").append("p").html("DotCount == " + AirItalyDotCounter + " Index " + i ); // d3.selectAll("body").append("p").html( AirItalyMaxArray[0] ); // d3.selectAll("body").append("p").html(d3.select(this).attr("id") + " - index -===>>>> " + i + " - Air Italy Dot Counter -===>>>> " + AirItalyDotCounter ); // d3.selectAll("body").append("p").html(d3.select(this).attr("cx")); // d3.selectAll("body").append("p").html(d3.select(this).attr("cy")); } }); var AirCanadaDotCounter = -2; var AirCanadaMinArray = []; var AirCanadaMaxArray = []; svg.selectAll(".DOTS") // <-- A .each(function(d, i) { if(d3.select(this).attr("id") == "Air Canada" ) { AirCanadaDotCounter += 3; AirCanadaMinArray.push( d3.select(this).attr("cx") ); AirCanadaMaxArray.push( d3.select(this).attr("cy") ); // d3.selectAll("body").append("p").html("DotCount == " + AirCanadaDotCounter ); // d3.selectAll("body").append("p").html(" Index " + i ); } }); // d3.selectAll("body").append("p").html(" Min == " + AirBalticMinArray[i] + " Max == " + AirBalticMaxArray[i] ); // d3.selectAll("body").append("p").html(" MinArray == " + Math.min(AirBalticMinArray[i]) + " MaxnArray == " + Math.min(AirBalticMaxArray[i]) ); // d3.selectAll("body").append("p").html("DotArray Is == " + Math.max(DotArray[i]) + " " + AirBalticMinArray[0] + " " + Math.max(AirBalticMinArray[i])); // for(var i = 0; i < DotArray.length; i++) // { // d3.selectAll("body").append("p").html("DotArray Is == " + DotArray[i] ); // } data1 = [{ //--------- Line One source: { x: AirBalticMaxArray[0], y: AirBalticMinArray[0], ID: "AirBaltic" }, target: { x: AirBalticMaxArray[1], y: AirBalticMinArray[1], ID: "AirBaltic" } }, //--------- Line Two { source: { x: AirBalticMaxArray[1], y: AirBalticMinArray[1], ID: "AirBaltic" }, target: { x: AirBalticMaxArray[2], y: AirBalticMinArray[2], ID: "AirBaltic" } } , //--------- Line Three { source: { x: AirBalticMaxArray[2], y: AirBalticMinArray[2], ID: "AirBaltic" }, target: { x: AirBalticMaxArray[3], y: AirBalticMinArray[3], ID: "AirBaltic" } } , //--------- Line Four { source: { x: AirBalticMaxArray[3], y: AirBalticMinArray[3], ID: "AirBaltic" }, target: { x: AirBalticMaxArray[4], y: AirBalticMinArray[4], ID: "AirBaltic" } } , //--------- Air Canada One { source: { x: AirCanadaMaxArray[0], y: AirCanadaMinArray[0], ID: "AirCanada" }, target: { x: AirCanadaMaxArray[1], y: AirCanadaMinArray[1], ID: "AirCanada" } } , //--------- Air Canada Two { source: { x: AirCanadaMaxArray[1], y: AirCanadaMinArray[1], ID: "AirCanada" }, target: { x: AirCanadaMaxArray[2], y: AirCanadaMinArray[2], ID: "AirCanada" } } , //--------- Air Canada Three { source: { x: AirCanadaMaxArray[2], y: AirCanadaMinArray[2], ID: "AirCanada" }, target: { x: AirCanadaMaxArray[3], y: AirCanadaMinArray[3], ID: "AirCanada" } } , //--------- Air Canada Four { source: { x: AirCanadaMaxArray[3], y: AirCanadaMinArray[3], ID: "AirCanada" }, target: { x: AirCanadaMaxArray[4], y: AirCanadaMinArray[4], ID: "AirCanada" } } , //--------- Air Italy Two { source: { x: AirItalyMaxArray[0], y: AirItalyMinArray[0], ID: "AirItaly" }, target: { x: AirItalyMaxArray[1], y: AirItalyMinArray[1], ID: "AirItaly" } } , //--------- Air Italy Three { source: { x: AirItalyMaxArray[1], y: AirItalyMinArray[1], ID: "AirItaly" }, target: { x: AirItalyMaxArray[2], y: AirItalyMinArray[2], ID: "AirItaly" } } , //--------- Air Italy Four { source: { x: AirItalyMaxArray[2], y: AirItalyMinArray[2], ID: "AirItaly" }, target: { x: AirItalyMaxArray[3], y: AirItalyMinArray[3], ID: "AirItaly" } } , //--------- Air Italy Four { source: { x: AirItalyMaxArray[3], y: AirItalyMinArray[3], ID: "AirItaly" }, target: { x: AirItalyMaxArray[4], y: AirItalyMinArray[4], ID: "AirItaly" } } , ]; // d3.select(".OneClass") // .remove(); // var one = d3.select("svg").append("svg") // .attr("class", "OneClass"); var link = d3.linkHorizontal() .x(function(d) { return d.y; }) .y(function(d) { return d.x; }); //d3.select(".TwoClass").remove(); d3.selectAll('.DOTS').on('click', function() { alert(d3.select(this).attr('id') + " " + d3.select(this).attr('cx') + " , " + d3.select(this).attr('cy') ); }); var x = d3.select('circle').datum(function() { return +d3.select(this).attr('cx') }); var y = d3.selectAll('circle').datum(function() { return +d3.select(this).attr('cy') }); var circleBox = circle.node().getBBox(); //Then, use those coordinates to set the x and y positions: // .attr("x", circleBox.x + circleBox.width/2 - widthMarker/2) // .attr("y",circleBox.y + circleBox.height/2 - widthMarker) // source: { // y: 0, // x: 167 // }, // target: { // y: 800, // x: 0 // } var Coordinates = []; Coordinates.push( { source: { y: circleBox.y, x: circleBox.x }, target: { y: circleBox.y, x: circleBox.x } , source: { y: circleBox.y, x: circleBox.x }, target: { y: circleBox.y, x: circleBox.x } }) // d3.select("body").append("p").html(" Data1 Is === === "+ JSON.stringify(data1)); // d3.select("body").append("p").html(" Data2 Is === === "+ JSON.stringify(Coordinates) ); // d3.select("body").append("p").html(" CircleBox.x === " + circleBox.x + " CircleBox.y " + JSON.stringify(circleBox)); svg.selectAll(null) // .attr("class", "TwoClass") //.data(Coordinates) .data(data1) .enter() .append("path") .attr("fill", "none") .style("stroke", function(d){ if(d.source.ID == "AirBaltic"){ return "#b3d1ff" } else if(d.source.ID == "AirItaly"){ return "#4d94ff" } else if(d.source.ID == "AirCanada"){ return "#002966" } }) .attr("stroke-width", "1.5px") .style("opacity", "4") .attr("d", link);}