window.onload = function(){
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};var width = 600 - margin.left - margin.right;
var height = 270 - margin.top - margin.bottom;
var parseDate = d3.timeFormat("%c").parse;
var x = d3.scaleLinear().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
var xAxis = d3.axisBottom()
.scale(x).ticks(5);
var yAxis = d3.axisLeft()
.scale(y).ticks(5);
var valueline = d3.line()
.x(function (d) {
return x(d.date);
})
.y(function (d) {
return y(d.close);
});
var svg = d3.select("body")
.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 + ")");
// Get the data
var data = [{
date: "1 ",
close: "58.13"
}, {
date: "2 ",
close: "53.98"
}, {
date: "3 ",
close: "67.00"
}, {
date: "4 ",
close: "89.70"
}, {
date: "5 ",
close: "99.00"
}, {
date: "6 ",
close: "20.00"
}];
var data2 = [{
date: "1 ",
close: "52.13"
}, {
date: "2 ",
close: "30.98"
}, {
date: "3 ",
close: "36.00"
}, {
date: "4 ",
close: "40.70"
}, {
date: "5 ",
close: "20.00"
}, {
date: "6 ",
close: "96.00"
}];
data.forEach(function (d) {
d.date = d.date;
d.close = +d.close;
});
// scaleLinear the range of the data
x.domain(d3.extent(data, function (d) {
return d.date;
}));
y.domain([0, d3.max(data, function (d) {
return d.close;
})]);
svg.append("path") // Add the valueline path.
.attr("d", valueline(data)).attr("stroke","red");
svg.append("path") // Add the valueline path.
.attr("d", valueline(data2)).attr("stroke","blue");
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
}
I am new to this. I want to add color to the stroke I am using but I am unable to do it. I have added attribute for applying stroke color in the code but it is not working. I want each of the line to be of different color. Please help me with the feasible solution.
Your code seems to work fine. Here is the d3 way of implementation for the same.
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};
var width = 600 - margin.left - margin.right;
var height = 270 - margin.top - margin.bottom;
var parseDate = d3.timeFormat("%c").parse;
var x = d3.scaleLinear().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
var xAxis = d3.axisBottom()
.scale(x).ticks(5);
var yAxis = d3.axisLeft()
.scale(y).ticks(5);
var valueline = d3.line()
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.close);
});
var colors = d3.scaleOrdinal(d3.schemeCategory10);
var svg = d3.select("body")
.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 + ")");
// Get the data
var data = [{
date: "1 ",
close: "58.13"
}, {
date: "2 ",
close: "53.98"
}, {
date: "3 ",
close: "67.00"
}, {
date: "4 ",
close: "89.70"
}, {
date: "5 ",
close: "99.00"
}, {
date: "6 ",
close: "20.00"
}];
var data2 = [{
date: "1 ",
close: "52.13"
}, {
date: "2 ",
close: "30.98"
}, {
date: "3 ",
close: "36.00"
}, {
date: "4 ",
close: "40.70"
}, {
date: "5 ",
close: "20.00"
}, {
date: "6 ",
close: "96.00"
}];
data.forEach(function(d) {
d.date = d.date;
d.close = +d.close;
});
// scaleLinear the range of the data
x.domain(d3.extent(data, function(d) {
return d.date;
}));
y.domain([0, d3.max(data, function(d) {
return d.close;
})]);
svg.selectAll("path.line").data([data, data2])
.enter().
append("path") // Add the valueline path.
.attr("class", "line")
.attr("d", valueline)
.attr("stroke", function(d, i) {
return colors(i);
});
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
path {
fill: none;
}
<script src="https://d3js.org/d3.v4.min.js"></script>d
Related
Assuming I have data like this:
const data = [
{
month: 1
apples: ...,
bananas: ...,
cherries: ...,
dates: ...,
},
{
month: 2
apples: ...,
bananas: ...,
cherries: ...,
dates: ...,
},
{
month: 3
apples: ...,
bananas: ...,
cherries: ...,
dates: ...,
}
]
Going for 12 months, using keys of ['apples','bananas','cherries','dates']. The d3.stack() will produce an array for 4 bars with 12 sets of values. This makes sense. However, what if I wanted to create 12 bars with the keys broken up so it's sets of 4 values.
Is it possible to flip things on their heads in this fashion?
You just need to convert the data into the required format and flip the axis and data configurations in the chart as shown below.
Existing :
var margin = {
top: 20,
right: 160,
bottom: 35,
left: 30
};
var width = 500 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom;
var svg = d3.select("body")
.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 + ")");
/* Data in strings like it would be if imported from a csv */
var data = [{
year: "2006",
redDelicious: "10",
mcintosh: "15",
oranges: "9",
pears: "6"
},
{
year: "2007",
redDelicious: "12",
mcintosh: "18",
oranges: "9",
pears: "4"
},
{
year: "2008",
redDelicious: "05",
mcintosh: "20",
oranges: "8",
pears: "2"
},
{
year: "2009",
redDelicious: "01",
mcintosh: "15",
oranges: "5",
pears: "4"
}
];
var parse = d3.time.format("%Y").parse;
// Transpose the data into layers
var dataset = d3.layout.stack()(["redDelicious", "mcintosh", "oranges", "pears"].map(function(fruit) {
return data.map(function(d) {
return {
x: parse(d.year),
y: +d[fruit]
};
});
}));
// Set x, y and colors
var x = d3.scale.ordinal()
.domain(dataset[0].map(function(d) {
return d.x;
}))
.rangeRoundBands([10, width - 10], 0.02);
var y = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) {
return d3.max(d, function(d) {
return d.y0 + d.y;
});
})])
.range([height, 0]);
var colors = ["b33040", "#d25c4d", "#f2b447", "#d9d574"];
// Define and draw axes
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5)
.tickSize(-width, 0, 0)
.tickFormat(function(d) {
return d
});
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(d3.time.format("%Y"));
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Create groups for each series, rects for each segment
var groups = svg.selectAll("g.cost")
.data(dataset)
.enter().append("g")
.attr("class", "cost")
.style("fill", function(d, i) {
return colors[i];
});
var rect = groups.selectAll("rect")
.data(function(d) {
return d;
})
.enter()
.append("rect")
.attr("x", function(d) {
return x(d.x);
})
.attr("y", function(d) {
return y(d.y0 + d.y);
})
.attr("height", function(d) {
return y(d.y0) - y(d.y0 + d.y);
})
.attr("width", x.rangeBand())
.on("mouseover", function() {
tooltip.style("display", null);
})
.on("mouseout", function() {
tooltip.style("display", "none");
})
.on("mousemove", function(d) {
var xPosition = d3.mouse(this)[0] - 15;
var yPosition = d3.mouse(this)[1] - 25;
tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
tooltip.select("text").text(d.y);
});
// Draw legend
var legend = svg.selectAll(".legend")
.data(colors)
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) {
return "translate(30," + i * 19 + ")";
});
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", function(d, i) {
return colors.slice().reverse()[i];
});
legend.append("text")
.attr("x", width + 5)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "start")
.text(function(d, i) {
switch (i) {
case 0:
return "Anjou pears";
case 1:
return "Naval oranges";
case 2:
return "McIntosh apples";
case 3:
return "Red Delicious apples";
}
});
// Prep the tooltip bits, initial display is hidden
var tooltip = svg.append("g")
.attr("class", "tooltip")
.style("display", "none");
tooltip.append("rect")
.attr("width", 30)
.attr("height", 20)
.attr("fill", "white")
.style("opacity", 0.5);
tooltip.append("text")
.attr("x", 15)
.attr("dy", "1.2em")
.style("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold");
svg {
font: 10px sans-serif;
shape-rendering: crispEdges;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
}
path.domain {
stroke: none;
}
.y .tick line {
stroke: #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
New :
var margin = {
top: 20,
right: 160,
bottom: 35,
left: 30
};
var width = 500 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom;
var svg = d3.select("body")
.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 + ")");
/* Data in strings like it would be if imported from a csv */
var data = [{
fruit: "redDelicious",
2006: "10",
2007: "12",
2008: "05",
2009: "01",
2010: "02"
},
{
fruit: "mcintosh",
2006: "15",
2007: "18",
2008: "20",
2009: "15",
2010: "10"
},
{
fruit: "oranges",
2006: "9",
2007: "9",
2008: "8",
2009: "5",
2010: "4"
},
{
fruit: "pears",
2006: "6",
2007: "4",
2008: "2",
2009: "4",
2010: "2"
}
];
var legends = Object.keys(data[0]);
legends.splice(legends.indexOf('fruit'), 1);
// Transpose the data into layers
var dataset = d3.layout.stack()(legends.map(function(year) {
return data.map(function(d) {
return {
x: d.fruit,
y: +d[year]
};
});
}));
// Set x, y and colors
var x = d3.scale.ordinal()
.domain(dataset[0].map(function(d) {
return d.x;
}))
.rangeRoundBands([10, width - 10], 0.02);
var y = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) {
return d3.max(d, function(d) {
return d.y0 + d.y;
});
})])
.range([height, 0]);
var colors = ["b33040", "#d25c4d", "#f2b447", "#d9d574","#6aa8e0"];
// Define and draw axes
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5)
.tickSize(-width, 0, 0)
.tickFormat(function(d) {
return d
});
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
//.tickFormat(d3.time.format("%Y"));
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Create groups for each series, rects for each segment
var groups = svg.selectAll("g.cost")
.data(dataset)
.enter().append("g")
.attr("class", "cost")
.style("fill", function(d, i) {
return colors[i];
});
var rect = groups.selectAll("rect")
.data(function(d) {
return d;
})
.enter()
.append("rect")
.attr("x", function(d) {
return x(d.x);
})
.attr("y", function(d) {
return y(d.y0 + d.y);
})
.attr("height", function(d) {
return y(d.y0) - y(d.y0 + d.y);
})
.attr("width", x.rangeBand())
.on("mouseover", function() {
tooltip.style("display", null);
})
.on("mouseout", function() {
tooltip.style("display", "none");
})
.on("mousemove", function(d) {
var xPosition = d3.mouse(this)[0] - 15;
var yPosition = d3.mouse(this)[1] - 25;
tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
tooltip.select("text").text(d.y);
});
// Draw legend
var legend = svg.selectAll(".legend")
.data(colors)
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) {
return "translate(30," + i * 19 + ")";
});
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", function(d, i) {
return colors.slice().reverse()[i];
});
legend.append("text")
.attr("x", width + 5)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "start")
.text(function(d, i) {
return legends.reverse()[i];
});
// Prep the tooltip bits, initial display is hidden
var tooltip = svg.append("g")
.attr("class", "tooltip")
.style("display", "none");
tooltip.append("rect")
.attr("width", 30)
.attr("height", 20)
.attr("fill", "white")
.style("opacity", 0.5);
tooltip.append("text")
.attr("x", 15)
.attr("dy", "1.2em")
.style("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold");
svg {
font: 10px sans-serif;
shape-rendering: crispEdges;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
}
path.domain {
stroke: none;
}
.y .tick line {
stroke: #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Based on Simple graph with grid lines in v4 (for example), I would like to add laced bands between grid lines, similar to the picture below:
How could I achieve that?
Thanks.
I was able to solve this using rect elements and enabling opacity based on their index. First I get all the values of the yaxis into an array so that I can get the y attribute for each rect and then just append those rects in a group g.
// add the Y Axis
svg.append("g").attr('class', 'y axis')
.call(d3.axisLeft(y));
//Store all values of the y-axis to an array
var yval = []
d3.selectAll('.y.axis>g>text').each(function(d) {
yval.push(d);
});
// Create rects and assign opacity based on index
rects.selectAll('rect').data(yval).enter().append('rect')
.attr('x', 0).attr('y', function(d) { return y(d); })
.attr('height', height / yval.length)
.attr('width', width).style('fill-opacity', function(d, i) {
if (i == 0) {
return 0;
}
if (i % 2 == 0) {
return 0.1;
} else {
return 0;
}
});
// 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("%d-%b-%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.close);
});
// 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("body").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 + ")");
// gridlines in x axis function
function make_x_gridlines() {
return d3.axisBottom(x)
.ticks(5)
}
// gridlines in y axis function
function make_y_gridlines() {
return d3.axisLeft(y)
.ticks(5)
}
// Get the data
var data = [{
"date": "1-May-12",
"close": 58.13
},
{
"date": "30-Apr-12",
"close": 53.98
},
{
"date": "27-Apr-12",
"close": 67
},
{
"date": "26-Apr-12",
"close": 89.7
},
{
"date": "25-Apr-12",
"close": 99
},
{
"date": "24-Apr-12",
"close": 130.28
},
{
"date": "23-Apr-12",
"close": 166.7
},
{
"date": "20-Apr-12",
"close": 234.98
},
{
"date": "19-Apr-12",
"close": 345.44
},
{
"date": "18-Apr-12",
"close": 443.34
},
{
"date": "17-Apr-12",
"close": 543.7
},
{
"date": "16-Apr-12",
"close": 580.13
},
{
"date": "13-Apr-12",
"close": 605.23
},
{
"date": "12-Apr-12",
"close": 622.77
},
{
"date": "11-Apr-12",
"close": 626.2
},
{
"date": "10-Apr-12",
"close": 628.44
},
{
"date": "9-Apr-12",
"close": 636.23
},
{
"date": "5-Apr-12",
"close": 633.68
},
{
"date": "4-Apr-12",
"close": 624.31
},
{
"date": "3-Apr-12",
"close": 629.32
},
{
"date": "2-Apr-12",
"close": 618.63
},
{
"date": "30-Mar-12",
"close": 599.55
},
{
"date": "29-Mar-12",
"close": 609.86
},
{
"date": "28-Mar-12",
"close": 617.62
},
{
"date": "27-Mar-12",
"close": 614.48
},
{
"date": "26-Mar-12",
"close": 606.98
}
]
// format the data
data.forEach(function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
});
// 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 d.close;
})]);
// add the X gridlines
svg.append("g")
.attr("class", "grid")
.attr("transform", "translate(0," + height + ")")
.call(make_x_gridlines()
.tickSize(-height)
.tickFormat("")
)
// add the Y gridlines
svg.append("g")
.attr("class", "grid")
.call(make_y_gridlines()
.tickSize(-width)
.tickFormat("")
)
var rects = svg.append('g').attr('class', 'intBands')
// 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").attr('class', 'y axis')
.call(d3.axisLeft(y));
var yval = []
d3.selectAll('.y.axis>g>text').each(function(d) {
yval.push(d);
});
rects.selectAll('rect').data(yval).enter().append('rect')
.attr('x', 0).attr('y', function(d) {
return y(d)
}).attr('height', height / yval.length).attr('width', width).style('fill-opacity', function(d, i) {
if (i == 0) {
return 0;
}
if (i % 2 == 0) {
return 0.1;
} else {
return 0;
}
});
.line {
fill: none;
stroke: steelblue;
stroke-width: 2px;
}
.grid line {
stroke: lightgrey;
stroke-opacity: 0.7;
shape-rendering: crispEdges;
}
.grid path {
stroke-width: 0;
}
<!DOCTYPE html>
<meta charset="utf-8">
<style>
/* set the CSS */
</style>
<body>
<!-- load the d3.js library -->
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
</script>
</body>
If anyone has a better way of doing this, please post your solution. Thanks.
One way consists in getting ranges between grid lines from the y-axis and for each of them to include a rectangle:
// 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("%d-%b-%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.close); });
// 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("body").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 + ")");
// gridlines in x axis function
function make_x_gridlines() {
return d3.axisBottom(x)
.ticks(5)
}
// gridlines in y axis function
function make_y_gridlines() {
return d3.axisLeft(y)
.ticks(5)
}
// Get the data
var data = [
{ date: "1-May-12", close: 58.13 },
{ date: "30-Apr-12", close: 53.98 },
{ date: "27-Apr-12", close: 67.00 },
{ date: "26-Apr-12", close: 89.70 },
{ date: "25-Apr-12", close: 99.00 },
{ date: "24-Apr-12", close: 130.28 },
{ date: "23-Apr-12", close: 166.70 },
{ date: "20-Apr-12", close: 234.98 },
{ date: "19-Apr-12", close: 345.44 },
{ date: "18-Apr-12", close: 443.34 },
{ date: "17-Apr-12", close: 543.70 },
{ date: "16-Apr-12", close: 580.13 },
{ date: "13-Apr-12", close: 605.23 },
{ date: "12-Apr-12", close: 622.77 },
{ date: "11-Apr-12", close: 626.20 },
{ date: "10-Apr-12", close: 628.44 },
{ date: "9-Apr-12", close: 636.23 },
{ date: "5-Apr-12", close: 633.68 },
{ date: "4-Apr-12", close: 624.31 },
{ date: "3-Apr-12", close: 629.32 },
{ date: "2-Apr-12", close: 618.63 },
{ date: "30-Mar-12", close: 599.55 },
{ date: "29-Mar-12", close: 609.86 },
{ date: "28-Mar-12", close: 617.62 },
{ date: "27-Mar-12", close: 614.48 },
{ date: "26-Mar-12", close: 606.98 }
]
// d3.csv("data.csv").then(data) {
// format the data
data.forEach(function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
});
// 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 d.close; })]);
// add the X gridlines
svg.append("g")
.attr("class", "grid")
.attr("transform", "translate(0," + height + ")")
.call(make_x_gridlines()
.tickSize(-height)
.tickFormat("")
)
// add the Y gridlines
svg.append("g")
.attr("class", "grid ylines")
.call(make_y_gridlines()
.tickSize(-width)
.tickFormat("")
)
// 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));
var bands = [];
var start;
d3.selectAll(".ylines .tick line")
.each(function(d, i) {
if (i % 2 == 0)
start = d;
else {
bands.push({ "start": start, "end": d })
start = null;
}
});
// If it remains the top band:
if (start)
bands.push({ "start": start, "end": d3.max(data, function(d) { return d.close; }) })
svg.append("g").selectAll("band")
.data(bands)
.enter().append("rect")
.attr("y", d => y(d.end))
.attr("height", d => y(d.start) - y(d.end))
.attr("x", d => 0)
.attr("width", d => width)
.style("opacity", 0.1)
.style("stroke", "#005e23")
.style("fill", "#005e23");
// });
.line {
fill: none;
stroke: steelblue;
stroke-width: 2px;
}
.grid line {
stroke: lightgrey;
stroke-opacity: 0.7;
shape-rendering: crispEdges;
}
.grid path {
stroke-width: 0;
}
<body>
<script src="https://d3js.org/d3.v5.min.js"></script>
</body>
// Let's retrieve from the grid lines the associated bands y-extremities:
var bands = [];
var start;
d3.selectAll(".ylines .tick line")
.each(function(d, i) {
if (i % 2 == 0)
start = d;
else {
bands.push({ "start": start, "end": d })
start = null; // in order to know if we should use the top band
}
});
// If it remains a top band:
if (start)
bands.push({ "start": start, "end": d3.max(data, function(d) { return d.close; }) })
// Our bands look like:
// [{start: 0,end: 100}, {start: 200,end: 300}, ..., {start: 600,end: 636.23}]
svg.append("g").selectAll("band")
.data(bands)
.enter().append("rect")
.attr("y", d => y(d.end))
.attr("height", d => y(d.start) - y(d.end))
.attr("x", d => 0)
.attr("width", d => width)
.style("opacity", 0.1)
.style("stroke", "#005e23")
.style("fill", "#005e23");
Using grid lines rather than ticks gives the choice to have more ticks than grid lines.
I am trying to follow this https://bl.ocks.org/mbostock/34f08d5e11952a80609169b7917d4172
Here is my fiddle: https://jsfiddle.net/q0xece4k/17/'
<!DOCTYPE html>
<meta charset="utf-8">
<title>Plotting a Trendline with D3.js</title>
<style>
.line {
stroke: blue;
fill:none;
stroke-width: 3;
}
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-size: 10px;
font-family: sans-serif;
}
.text-label {
font-size: 10px;
font-family: sans-serif;
}
.zoom {
cursor: move;
fill: none;
pointer-events: all;
}
</style>
<div>
<div id="container"></div>
</div>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script>
var height = 300;
var width = 600;
var margin = {top: 10, right:20, bottom: 50, left: 40};
// formatters for axis and labels
var rateFormat = d3.format("0.1f");
var trendDataArr = [
{
date: "2017-01-29",
value: 87.1
},
{
date: "2017-02-06",
value: 88
},
{
date: "2017-02-13",
value: 86.8
},
{
date: "2017-02-20",
value: 86.8
},
{
date: "2017-02-27",
value: 87.1
},
{
date: "2017-03-05",
value: 85.8
},
{
date: "2017-03-12",
value: 85.5
},
{
date: "2017-03-19",
value: 87.1
},
{
date: "2017-03-26",
value: 88
},
{
date: "2017-04-02",
value: 87.4
},
{
date: "2017-04-09",
value: 86.8
},
{
date: "2017-04-16",
value: 87.1
},
{
date: "2017-04-23",
value: 87.4
},
{
date: "2017-04-30",
value: 85.8
},
{
date: "2017-05-07",
value: 86.5
},
{
date: "2017-05-14",
value: 87.1
},
{
date: "2017-05-21",
value: 86.9
},
{
date: "2017-05-28",
value: 87.7
},
{
date: "2017-06-04",
value: 87.8
}
];
var zoom = d3.zoom()
.scaleExtent([1, Infinity])
.translateExtent([[0, 0], [width, height]])
.extent([[0, 0], [width, height]])
.on("zoom", zoomed);
var svg = d3.select('#container')
.append("svg")
.attr("pointer-events", "all")
.attr("width", 1000 + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.append("g");
svg.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom);
svg.append("g")
.attr("class", "y axis");
svg.append("g")
.attr("class", "x axis");
function getDate(d) {
return moment(d["date"],"YYYY-MM-DD").toDate();
}
function removeDuplicates(xLabels){
var result = [];
xLabels.forEach(function(item) {
if(result.indexOf(item) < 0) {
result.push(item);
}
return result;
});
}
var minDate = getDate(trendDataArr[0]),
maxDate = getDate(trendDataArr[trendDataArr.length-1]);
var xScale = d3.scaleTime()
// .rangeBands([margin.left, width-100], .1);
.domain([minDate, maxDate])
.range([margin.left, width])
// .nice(trendDataArr.length);
var yScale = d3.scaleLinear()
.range([height, 0]);
var xAxis = d3.axisBottom(xScale)
.tickFormat(d3.timeFormat('%d %b %y'));
var yAxis = d3.axisLeft(yScale);
var xLabels = trendDataArr.map(function (d) { return getDate(d); });
xScale.domain(d3.extent(xLabels));
yScale.domain([Math.round(d3.min(trendDataArr, function(d) { return parseFloat(d['value']); }))-5, Math.round(d3.max(trendDataArr, function(d) { return parseFloat(d['value']); }))+5]);
var line = d3.line()
.x(function(d) { return xScale(getDate(d)); })
.y(function(d) { return yScale(d['value']); })
.curve(d3.curveCardinal);
svg.append("path")
.datum(trendDataArr)
.attr('fill','none')
.attr("d", line(trendDataArr.filter(function(d) {
return d;
}
)
)
)
.attr('stroke', "steelblue")
.attr('stroke-width', 2);
svg.select(".x.axis")
.attr("transform", "translate(0," + (height+5) + ")")
.call(xAxis.tickFormat(d3.timeFormat("%d %b %y")))
.selectAll("text")
.style("text-anchor","end")
.attr("transform", function(d) {
return "rotate(-45) ";
});
svg.select(".y.axis")
.attr("transform", "translate(" + (margin.left) + ",0)")
.call(yAxis.tickFormat(rateFormat));
// chart title
svg.append("text")
.attr("x", (width + (margin.left + margin.right) )/ 2 -200)
.attr("y", 0 + margin.top -20)
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("font-family", "sans-serif")
.text("Zoomable chart");
//y axis label
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -20)
.attr("x",0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Rate");
function zoomed() {
var t = d3.event.transform;
xScale.domain(t.rescaleX(xScale).domain());
}
</script>
</body>
Could someone help me with the zooming in/out on the axis so that I can drill into each day or zoom out to years?
I got it to work:
here is the updated fiddle:
https://jsfiddle.net/q0xece4k/17/
var height = 300;
var width = 600;
var margin = {top: 10, right:20, bottom: 50, left: 40};
// formatters for axis and labels
var rateFormat = d3.format("0.1f");
var trendDataArr = [
{
date: "2017-01-29",
value: 87.1
},
{
date: "2017-02-06",
value: 88
},
{
date: "2017-02-13",
value: 86.8
},
{
date: "2017-02-20",
value: 86.8
},
{
date: "2017-02-27",
value: 87.1
},
{
date: "2017-03-05",
value: 85.8
},
{
date: "2017-03-12",
value: 85.5
},
{
date: "2017-03-19",
value: 87.1
},
{
date: "2017-03-26",
value: 88
},
{
date: "2017-04-02",
value: 87.4
},
{
date: "2017-04-09",
value: 86.8
},
{
date: "2017-04-16",
value: 87.1
},
{
date: "2017-04-23",
value: 87.4
},
{
date: "2017-04-30",
value: 85.8
},
{
date: "2017-05-07",
value: 86.5
},
{
date: "2017-05-14",
value: 87.1
},
{
date: "2017-05-21",
value: 86.9
},
{
date: "2017-05-28",
value: 87.7
},
{
date: "2017-06-04",
value: 87.8
}
];
var zoom = d3.zoom()
.scaleExtent([1, Infinity])
.translateExtent([[0, 0], [width, height]])
.extent([[0, 0], [width, height]])
.on("zoom", zoomed);
var svg = d3.select('#container')
.append("svg")
.attr("pointer-events", "all")
.attr("width", 1000 + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.append("g");
svg.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom);
svg.append("g")
.attr("class", "y axis");
svg.append("g")
.attr("class", "x axis");
function getDate(d) {
return moment(d["date"],"YYYY-MM-DD").toDate();
}
function removeDuplicates(xLabels){
var result = [];
xLabels.forEach(function(item) {
if(result.indexOf(item) < 0) {
result.push(item);
}
return result;
});
}
var minDate = getDate(trendDataArr[0]),
maxDate = getDate(trendDataArr[trendDataArr.length-1]);
var xScale = d3.scaleTime()
// .rangeBands([margin.left, width-100], .1);
.domain([minDate, maxDate])
.range([margin.left, width])
// .nice(trendDataArr.length);
var yScale = d3.scaleLinear()
.range([height, 0]);
var xAxis = d3.axisBottom(xScale)
.tickFormat(d3.timeFormat('%d %b %y'));
var yAxis = d3.axisLeft(yScale);
var xLabels = trendDataArr.map(function (d) { return getDate(d); });
xScale.domain(d3.extent(xLabels));
yScale.domain([Math.round(d3.min(trendDataArr, function(d) { return parseFloat(d['value']); }))-5, Math.round(d3.max(trendDataArr, function(d) { return parseFloat(d['value']); }))+5]);
var line = d3.line()
.x(function(d) { return xScale(getDate(d)); })
.y(function(d) { return yScale(d['value']); })
.curve(d3.curveCardinal);
svg.append("path")
.datum(trendDataArr)
.attr('fill','none')
.attr("d", line(trendDataArr.filter(function(d) {
return d;
}
)
)
)
.attr('stroke', "steelblue")
.attr('stroke-width', 2);
svg.select(".x.axis")
.attr("transform", "translate(0," + (height+5) + ")")
.call(xAxis.tickFormat(d3.timeFormat("%d %b %y")))
.selectAll("text")
.style("text-anchor","end")
.attr("transform", function(d) {
return "rotate(-45) ";
});
svg.select(".y.axis")
.attr("transform", "translate(" + (margin.left) + ",0)")
.call(yAxis.tickFormat(rateFormat));
// chart title
svg.append("text")
.attr("x", (width + (margin.left + margin.right) )/ 2 -200)
.attr("y", 0 + margin.top -20)
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("font-family", "sans-serif")
.text("Zoomable chart");
//y axis label
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -20)
.attr("x",0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Rate");
function zoomed() {
var t = d3.event.transform;
xScale.domain(t.rescaleX(xScale).domain());
}
You need to call xAxis again.
function zoomed() {
console.info('zoom called');
var t = d3.event.transform;
xScale.domain(t.rescaleX(xScale).domain());
svg.select(".x.axis")
.call(xAxis.tickFormat(d3.timeFormat("%d %b %y")));
}
This is not the complete solution as it just zooms xAxis and not the plot but it might help you in zooming the plot too.
Or you might want to refer: https://bl.ocks.org/deristnochda/1ffe16ccf8bed2035ea5091ab9bb53fb
I am learning d3 and trying to implement a specific functionality.
Data is not getting plotted properly. I am not able to find where it is going wrong.
Link to jsfiddle https://jsfiddle.net/4nc1nc95/1/
$(function() {
var width = 355;
var height = 142;
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 70
};
var scope = {
graphData: {
"data": [{
"YEAR": "FY16Q1",
"SAVINGS": null,
"SPEND": null
}, {
"YEAR": "FY16Q2",
"SAVINGS": null,
"SPEND": null
}, {
"YEAR": "FY16Q3",
"SAVINGS": null,
"SPEND": null
}, {
"YEAR": "FY16Q4",
"SAVINGS": "0.023961",
"SPEND": "7419879.04"
}, {
"YEAR": "FY17Q1",
"SAVINGS": "0.00618",
"SPEND": "34923499.71732"
}]
}
};
var x_domain = d3.extent(scope.graphData.data, function(d) {
return d.YEAR;
});
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .0)
.domain(scope.graphData.data.map(function(d) {
return d.YEAR;
}));
var y = d3.scale.linear()
.domain([0, 0.03])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5, "%");
var area = d3.svg.area()
.x(function(d) {
return x(d.YEAR);
})
.y0(height)
.y1(function(d) {
return y(d.SAVINGS);
});
var sampleSVG = d3.select('#area')
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + 62)
.append("g")
.attr("transform", "translate(" + margin.left + "," + (margin.top + 24) + ")");
sampleSVG.append("path")
.datum(scope.graphData.data)
.attr("class", "area")
.attr("d", area);
sampleSVG.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
sampleSVG.append("g")
.attr("class", "y axis")
.call(yAxis);
if (scope.mode == "restore") {
sampleSVG.append("g")
.append("text")
.attr("y", "-8%")
.attr("x", "-2%")
.attr("class", "heading tableHeader")
.text("SAVING");
}
})
Instead of:
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .0)
Use:
var x = d3.scale.ordinal()
.rangePoints([0, width], .0)
Here is your fiddle: https://jsfiddle.net/gerardofurtado/b1mzyxLq/
I am new in D3 js.most of the examples in gallery load data from TSV files.
but I wanted to render line graph using json in mvc3 razor. below is code where i hard code my data.please let me know how to retrive dynamic data using json.
var data = [
{ "date": 0, "close": 0.3372 },
{ "date": 1, "close": 1.7 },
{ "date": 2, "close": 1.8 },
{ "date": 3, "close": 2.014 },
{ "date": 4, "close": 10.995 },
{ "date": 5, "close": 16.227 },
{ "date": 6, "close": 16.643 },
{ "date": 7, "close": 20.644 },
{ "date": 8, "close": 22.478 }
];
var margin = { top: 20, right: 20, bottom: 30, left: 50 },
width = 600 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
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");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(function (d) { return x(d.date); })
.y(function (d) { return y(d.close); });
var svg = d3.select("body").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 + ")");
console.log("here");
data.forEach(function (d) {
d.date = parseInt(d.date);
d.close = +d.close;
});
console.log("here2");
x.domain(d3.extent(data, function (d) { return d.date; }));
y.domain(d3.extent(data, function (d) { return d.close; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.text("Request")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Probability");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);