d3 waterfall graph rotate in x axis values 180 to -90 degree - javascript

can you resolve this problem.
I am not able to rotate in X-axis values. can you please check below examples. Now x-axis text is coming horizontally but we wants Vertical alignment.
In my requirement is rotate -60 or -90 only. in "Model 1 , Module 2, Module 3" values i needs to rotate.
var margin = {top: 20, right: 30, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
padding = 0.3;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], padding);
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")
.tickFormat(function(d) { return dollarFormatter(d); });
var chart = d3.select(".chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//d3.csv("data.csv", type, function(error, data) {
var data = [{ name :"Module 1",value : 20 },{ name :"Module 2",value :15},{ name :"Module 3 ",value :45},
{ name :"Final Count ",value :200}];
//console.log(data);
// Transform data (i.e., finding cumulative values and total) for easier charting
var cumulative = 0;
for (var i = 0; i < data.length; i++) {
data[i].start = cumulative;
cumulative += data[i].value;
data[i].end = cumulative;
data[i].class = ( data[i].value >= 0 ) ? 'positive' : 'negative'
}
data.push({
name: 'Total',
end: cumulative,
start: 0,
class: 'total'
});
x.domain(data.map(function(d) { return d.name; }));
y.domain([0, d3.max(data, function(d) { return d.end; })]);
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
chart.append("g")
.attr("class", "y axis")
.call(yAxis);
var bar = chart.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("class", function(d) { return "bar " + d.class })
.attr("transform", function(d) { return "translate(" + x(d.name) + ",0)"; });
bar.append("rect")
.attr("y", function(d) { return y( Math.max(d.start, d.end) ); })
.attr("height", function(d) { return Math.abs( y(d.start) - y(d.end) ); })
.attr("width", x.rangeBand());
bar.append("text")
.attr("x", x.rangeBand() / 2)
.attr("y", function(d) { return y(d.end) + 5; })
.attr("dy", function(d) { return ((d.class=='negative') ? '-' : '') + ".75em" })
.text(function(d) { return dollarFormatter(d.end - d.start);});
bar.filter(function(d) { return d.class != "total" }).append("line")
.attr("class", "connector")
.attr("x1", x.rangeBand() + 5 )
.attr("y1", function(d) { return y(d.end) } )
.attr("x2", x.rangeBand() / ( 1 - padding) - 5 )
.attr("y2", function(d) { return y(d.end) } )
//});
function type(d) {
d.value = +d.value;
return d;
}
function dollarFormatter(n) {
n = Math.round(n);
var result = n;
if (Math.abs(n) > 1000) {
result = Math.round(n/1000) + 'K';
}
return result;
}
.bar.total rect {
fill: steelblue;
}
.bar.positive rect {
fill: darkolivegreen;
}
.bar.negative rect {
fill: crimson;
}
.bar line.connector {
stroke: grey;
stroke-dasharray: 3;
}
.bar text {
fill: white;
font: 10px sans-serif;
text-anchor: middle;
}
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
<script src="http://d3js.org/d3.v3.min.js"></script>
<svg class="chart"></svg>

To rotate only the first 3 ticks ("module 1", "module 2" and "module 3"):
var ticks = d3.selectAll(".x.axis text").each(function(d, i) {
if (i < 3) {
d3.select(this).attr("y", 0)
d3.select(this).attr("x", 10)
d3.select(this).attr("dy", ".35em")
d3.select(this).attr("transform", "rotate(90)")
d3.select(this).style("text-anchor", "start");
}
});
Check the demo:
var margin = {
top: 20,
right: 30,
bottom: 60,
left: 40
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
padding = 0.3;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], padding);
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")
.tickFormat(function(d) {
return dollarFormatter(d);
});
var chart = d3.select(".chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//d3.csv("data.csv", type, function(error, data) {
var data = [{
name: "Module 1",
value: 20
}, {
name: "Module 2",
value: 15
}, {
name: "Module 3 ",
value: 45
}, {
name: "Final Count ",
value: 200
}];
//console.log(data);
// Transform data (i.e., finding cumulative values and total) for easier charting
var cumulative = 0;
for (var i = 0; i < data.length; i++) {
data[i].start = cumulative;
cumulative += data[i].value;
data[i].end = cumulative;
data[i].class = (data[i].value >= 0) ? 'positive' : 'negative'
}
data.push({
name: 'Total',
end: cumulative,
start: 0,
class: 'total'
});
x.domain(data.map(function(d) {
return d.name;
}));
y.domain([0, d3.max(data, function(d) {
return d.end;
})]);
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
var ticks = d3.selectAll(".x.axis text").each(function(d, i) {
if (i < 3) {
d3.select(this).attr("y", 0)
d3.select(this).attr("x", 10)
d3.select(this).attr("dy", ".35em")
d3.select(this).attr("transform", "rotate(90)")
d3.select(this).style("text-anchor", "start");
}
});
chart.append("g")
.attr("class", "y axis")
.call(yAxis);
var bar = chart.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("class", function(d) {
return "bar " + d.class
})
.attr("transform", function(d) {
return "translate(" + x(d.name) + ",0)";
});
bar.append("rect")
.attr("y", function(d) {
return y(Math.max(d.start, d.end));
})
.attr("height", function(d) {
return Math.abs(y(d.start) - y(d.end));
})
.attr("width", x.rangeBand());
bar.append("text")
.attr("x", x.rangeBand() / 2)
.attr("y", function(d) {
return y(d.end) + 5;
})
.attr("dy", function(d) {
return ((d.class == 'negative') ? '-' : '') + ".75em"
})
.text(function(d) {
return dollarFormatter(d.end - d.start);
});
bar.filter(function(d) {
return d.class != "total"
}).append("line")
.attr("class", "connector")
.attr("x1", x.rangeBand() + 5)
.attr("y1", function(d) {
return y(d.end)
})
.attr("x2", x.rangeBand() / (1 - padding) - 5)
.attr("y2", function(d) {
return y(d.end)
})
//});
function type(d) {
d.value = +d.value;
return d;
}
function dollarFormatter(n) {
n = Math.round(n);
var result = n;
if (Math.abs(n) > 1000) {
result = Math.round(n / 1000) + 'K';
}
return result;
}
.bar.total rect {
fill: steelblue;
}
.bar.positive rect {
fill: darkolivegreen;
}
.bar.negative rect {
fill: crimson;
}
.bar line.connector {
stroke: grey;
stroke-dasharray: 3;
}
.bar text {
fill: white;
font: 10px sans-serif;
text-anchor: middle;
}
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
<script src="http://d3js.org/d3.v3.min.js"></script>
<svg class="chart"></svg>

Related

Fill line chart area with multiple colors

I am trying to create a chart like below:
While I've created the skeleton of it but stuck on how to fill those areas with multiple colors. I'm using d3 to complete this chart.
My code for reference:
var line = d3.line()
.x(function(d) { return x(d.ind); })
.y(function(d) { return y(d.tot_cases); })
x.domain(data.map(function(d) { return d.ind; }));
y.domain([0, d3.max(data, function(d) { return d.tot_cases; })]);
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
var lineAndDots = g.append("g")
.attr("class", "line-and-dots")
.attr("transform", "translate(" + ((margin.left + margin.right) / 3) + "," + 0 + ")")
// Data line
lineAndDots.append("path")
.datum(data)
.attr("class", "data-line")
.attr("d", line);
// Data dots
lineAndDots.selectAll("line-circle")
.data(data)
.enter().append("circle")
.attr("class", "data-circle")
.attr("r", 5)
.attr("cx", function(d) { return x(d.ind); })
.attr("cy", function(d) { return y(d.tot_cases); });
g.selectAll("lines-ax")
.data(data)
.enter().append("line")
.attr("class", "line")
.attr("x1", function(d) { return x(d.ind) + margin.right; })
.attr("y1", function(d) { return height - margin.bottom})
.attr("x2", function(d) { return x(d.ind) + margin.right ; })
.attr("y2", function(d) { return y(d.tot_cases); })
.attr("fill", "black")
.attr("stroke", "gray")
.attr("stroke-width", 3);
You can find my entire code in this link.
Any ideas on how to do this is very helpful. Thanks in advance!
Not a clean implementation, since I did not implement select, enter, append pattern of D3, also I add a random color generator, I will leave it to you to clean it up and add your color scheme to the chart
You might notice that the last element missing its color and polygon item since there is no indication on how to add it.
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 40},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
y = d3.scaleLinear().rangeRound([height, 0]);
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var data = [
{"ind": "Examined", tot_cases: 25000},
{"ind": "Notified", tot_cases: 17000},
{"ind": "Initiated", tot_cases: 10000},
{"ind": "HIV Stat. Confirmed", tot_cases: 14000},
{"ind": "HIV Unknown", tot_cases:15000}
]
var stroke_colors = {
"Examined": '#2B597C',
"Notified": "#6D5C7E",
"Initiated": '#BF6D84',
"HIV Stat. Confirmed": '#F1737E',
"HIV Unknown": '#F9B294'
}
var color = ["#2B597C","#6D5C7E","#BF6D84","#F1737E","#F9B294"]
var line = d3.line()
.x(function(d) { return x(d.ind); })
.y(function(d) { return y(d.tot_cases); })
x.domain(data.map(function(d) { return d.ind; }));
y.domain([0, d3.max(data, function(d) { return d.tot_cases; })]);
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
var lineAndDots = g.append("g")
.attr("class", "line-and-dots")
.attr("transform", "translate(" + ((margin.left + margin.right) / 3) + "," + 0 + ")")
// Data line
lineAndDots.append("path")
.datum(data)
.attr("class", "data-line")
.attr("d", line)
.style('stroke', function(d){
for(i = 0; i < 5; i++){
return stroke_colors[d[i].ind];}})
.style('fill', 'none')
// Data dots
lineAndDots.selectAll("line-circle")
.data(data)
.enter().append("circle")
.attr("class", "data-circle")
.attr("r", 5)
.attr("cx", function(d) { return x(d.ind); })
.attr("cy", function(d) { return y(d.tot_cases); })
g.selectAll("lines-ax")
.data(data)
.enter().append("line")
.attr("class", "line")
.attr("x1", function(d) { return x(d.ind) + margin.right; })
.attr("y1", function(d) { return height})
.attr("x2", function(d) { return x(d.ind) + margin.right ; })
.attr("fill", "black")
.attr("stroke", "#F2F2F2")
.attr("stroke-width", 3);
for(let i=1; i< data.length; i++) {
let points = [];
points[0] = {x: x(data[i-1].ind) + margin.right, y: y(data[i-1].tot_cases)};
points[1] = {x: x(data[i].ind) + + margin.right, y: y(data[i].tot_cases)};
points[2] = {x: x(data[i].ind) + + margin.right, y: height};
points[3] = {x: x(data[i-1].ind) + margin.right, y: height};
points[4] = {x: x(data[i-1].ind) + margin.right, y: y(data[i-1].tot_cases)};
g.append("polygon")
.attr("points", points.map(function(d) { return [d.x,d.y].join(","); }).join(" "))
.attr("stroke","red")
.attr("stroke-width", 2)
.attr('fill', getRandomRgb());
}
let points = [];
points[0] = {x: x(data[data.length - 1].ind) + margin.right, y: y(data[data.length - 1].tot_cases)};
points[1] = {x: x(data[data.length - 1].ind) + margin.right + 150, y: y(data[data.length - 1].tot_cases)};
points[2] = {x: x(data[data.length - 1].ind) + margin.right + 150, y: height};
points[3] = {x: x(data[data.length - 1].ind) + margin.right, y: height};
points[4] = {x: x(data[data.length - 1].ind) + margin.right, y: y(data[data.length - 1].tot_cases)};
g.append("polygon")
.attr("points", points.map(function(d) { return [d.x,d.y].join(","); }).join(" "))
.attr("stroke","red")
.attr("stroke-width", 2)
.attr('fill', getRandomRgb());
function getRandomRgb() {
const num = Math.round(0xffffff * Math.random());
const r = num >> 16;
const g = num >> 8 & 255;
const b = num & 255;
return 'rgb(' + r + ', ' + g + ', ' + b + ')';
}
body {
font-family: 'Droid Sans', sans-serif;
}
.axis {
font-size: 14px;
font-weight: bold;
}
text {
fill: #727075;
stroke: none;
}
.axis path,
.axis line {
fill: none;
stroke: none;
stroke-width: 2px;
shape-rendering: crispEdges;
}
.grid path {
stroke: none;
}
.grid line {
stroke: #E0E0E0;
shape-rendering: crispEdges;
}
.data-line {
fill: none;
stroke: url(#line-gradient);
stroke-width: 1px;
}
.data-circle {
fill: #3C92BA;
}
.axis-title {
text-anchor: end;
fill: #5D6971;
font-weight: normal;
}
.axis-tspan {
font-size: 12px;
}
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v5.min.js"></script>
</body>
</html>

How to make bar chart with additional vertical lines below the x axis

I want to make D3 bar chart with additional vertical lines on the x axis..
I checked one of the web sites in that below example.
I want make it like that graph, but I want an additional bottom line.
Can you please show me what to change?
var margin = {
top: 20,
right: 20,
bottom: 60,
left: 40
},
width = 560 - margin.left - margin.right,
height = 360 - margin.top - margin.bottom;
var color = {
Mechanical: '#4A7B9D',
Electrical: '#54577C',
Hydraulic: '#ED6A5A'
};
var barPadding = 40;
var data = [{
key: 'Mechanical',
values: [{
key: 'Gear',
value: 11
}, {
key: 'Bearing',
value: 8
}, {
key: 'Motor',
value: 3
}]
}, {
key: 'Electrical',
values: [{
key: 'Switch',
value: 19
}, {
key: 'Plug',
value: 12
}, {
key: 'Cord',
value: 11
}, {
key: 'Fuse',
value: 3
}, {
key: 'Bulb',
value: 2
}]
}, {
key: 'Hydraulic',
values: [{
key: 'Pump',
value: 4
}, {
key: 'Leak',
value: 3
}, {
key: 'Seals',
value: 1
}]
}];
var rangeBands = [];
var cummulative = 0;
data.forEach(function(val, i) {
val.cummulative = cummulative;
cummulative += val.values.length;
val.values.forEach(function(values) {
values.parentKey = val.key;
rangeBands.push(i);
})
});
//console.log(data);
var x_category = d3.scale.linear()
.range([0, width]);
var x_defect = d3.scale.ordinal().domain(rangeBands).rangeRoundBands([0, width], .1);
var x_category_domain = x_defect.rangeBand() * rangeBands.length;
x_category.domain([0, x_category_domain]);
var y = d3.scale.linear()
.range([height, 0]);
y.domain([0, d3.max(data, function(cat) {
return d3.max(cat.values, function(def) {
return def.value;
});
})]);
var category_axis = d3.svg.axis()
.scale(x_category)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.style('background-color', 'EFEFEF')
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
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("Value");
var category_g = svg.selectAll(".category")
.data(data)
.enter().append("g")
.attr("class", function(d) {
return 'category category-' + d.key;
})
.attr("transform", function(d) {
return "translate(" + x_category((d.cummulative * x_defect.rangeBand())) + ",0)";
})
.attr("fill", function(d) {
return color[d.key];
});
var category_label = category_g.selectAll(".category-label")
.data(function(d) {
return [d];
})
.enter().append("text")
.attr("class", function(d) {
//console.log(d)
return 'category-label category-label-' + d.key;
})
.attr("transform", function(d) {
var x_label = x_category((d.values.length * x_defect.rangeBand() + barPadding) / 2);
var y_label = height + 30;
return "translate(" + x_label + "," + y_label + ")";
})
.text(function(d) {
return d.key;
})
.attr('text-anchor', 'middle');
var defect_g = category_g.selectAll(".defect")
.data(function(d) {
return d.values;
})
.enter().append("g")
.attr("class", function(d) {
return 'defect defect-' + d.key;
})
.attr("transform", function(d, i) {
return "translate(" + x_category((i * x_defect.rangeBand())) + ",0)";
});
var defect_label = defect_g.selectAll(".defect-label")
.data(function(d) {
return [d];
})
.enter().append("text")
.attr("class", function(d) {
//console.log(d)
return 'defect-label defect-label-' + d.key;
})
.attr("transform", function(d) {
var x_label = x_category((x_defect.rangeBand() + barPadding) / 2);
var y_label = height + 10;
return "translate(" + x_label + "," + y_label + ")";
})
.text(function(d) {
return d.key;
})
.attr('text-anchor', 'middle');
var rects = defect_g.selectAll('.rect')
.data(function(d) {
return [d];
})
.enter().append("rect")
.attr("class", "rect")
.attr("width", x_category(x_defect.rangeBand() - barPadding))
.attr("x", function(d) {
return x_category(barPadding);
})
.attr("y", function(d) {
return y(d.value);
})
.attr("height", function(d) {
return height - y(d.value);
});
/* Styles go here */
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.bar {
fill: steelblue;
}
.x.axis path {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<script data-require="d3#3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Hello Plunker!</h1>
</body>
</html>
Try this way: -
category_g
.append("line")
.style("stroke", "black")
.style("stroke-width", "2px")
.style("stroke-linecap","round")
.attr("x1", function(d) {
var bbox = this.parentNode.getBBox();
return bbox.width+5;
})
.attr("y1", height)
.attr("x2", function(d) {
var bbox = this.parentNode.getBBox();
return bbox.width;
})
.attr("y2", height + 50);
var margin = {
top: 20,
right: 20,
bottom: 60,
left: 40
},
width = 560 - margin.left - margin.right,
height = 360 - margin.top - margin.bottom;
var color = {
Mechanical: '#4A7B9D',
Electrical: '#54577C',
Hydraulic: '#ED6A5A'
};
var barPadding = 40;
var data = [{
key: 'Mechanical',
values: [{
key: 'Gear',
value: 11
}, {
key: 'Bearing',
value: 8
}, {
key: 'Motor',
value: 3
}]
}, {
key: 'Electrical',
values: [{
key: 'Switch',
value: 19
}, {
key: 'Plug',
value: 12
}, {
key: 'Cord',
value: 11
}, {
key: 'Fuse',
value: 3
}, {
key: 'Bulb',
value: 2
}]
}, {
key: 'Hydraulic',
values: [{
key: 'Pump',
value: 4
}, {
key: 'Leak',
value: 3
}, {
key: 'Seals',
value: 1
}]
}];
var rangeBands = [];
var cummulative = 0;
data.forEach(function(val, i) {
val.cummulative = cummulative;
cummulative += val.values.length;
val.values.forEach(function(values) {
values.parentKey = val.key;
rangeBands.push(i);
})
});
//console.log(data);
var x_category = d3.scale.linear()
.range([0, width]);
var x_defect = d3.scale.ordinal().domain(rangeBands).rangeRoundBands([0, width], .1);
var x_category_domain = x_defect.rangeBand() * rangeBands.length;
x_category.domain([0, x_category_domain]);
var y = d3.scale.linear()
.range([height, 0]);
y.domain([0, d3.max(data, function(cat) {
return d3.max(cat.values, function(def) {
return def.value;
});
})]);
var category_axis = d3.svg.axis()
.scale(x_category)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.style('background-color', 'EFEFEF')
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
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("Value");
var category_g = svg.selectAll(".category")
.data(data)
.enter().append("g")
.attr("class", function(d) {
return 'category category-' + d.key;
})
.attr("transform", function(d) {
return "translate(" + x_category((d.cummulative * x_defect.rangeBand())) + ",0)";
})
.attr("fill", function(d) {
return color[d.key];
});
var category_label = category_g.selectAll(".category-label")
.data(function(d) {
return [d];
})
.enter().append("text")
.attr("class", function(d) {
//console.log(d)
return 'category-label category-label-' + d.key;
})
.attr("transform", function(d) {
var x_label = x_category((d.values.length * x_defect.rangeBand() + barPadding) / 2);
var y_label = height + 30;
return "translate(" + x_label + "," + y_label + ")";
})
.text(function(d) {
return d.key;
})
.attr('text-anchor', 'middle');
var defect_g = category_g.selectAll(".defect")
.data(function(d) {
return d.values;
})
.enter().append("g")
.attr("class", function(d) {
return 'defect defect-' + d.key;
})
.attr("transform", function(d, i) {
return "translate(" + x_category((i * x_defect.rangeBand())) + ",0)";
});
var defect_label = defect_g.selectAll(".defect-label")
.data(function(d) {
return [d];
})
.enter().append("text")
.attr("class", function(d) {
//console.log(d)
return 'defect-label defect-label-' + d.key;
})
.attr("transform", function(d) {
var x_label = x_category((x_defect.rangeBand() + barPadding) / 2);
var y_label = height + 10;
return "translate(" + x_label + "," + y_label + ")";
})
.text(function(d) {
return d.key;
})
.attr('text-anchor', 'middle');
var rects = defect_g.selectAll('.rect')
.data(function(d) {
return [d];
})
.enter().append("rect")
.attr("class", "rect")
.attr("width", x_category(x_defect.rangeBand() - barPadding))
.attr("x", function(d) {
return x_category(barPadding);
})
.attr("y", function(d) {
return y(d.value);
})
.attr("height", function(d) {
return height - y(d.value);
});
category_g
.append("line")
.style("stroke", "black")
.style("stroke-width", "4px")
.style("stroke-linecap","round")
.attr("x1", function(d) {
var bbox = this.parentNode.getBBox();
return bbox.width+7;
})
.attr("y1", height)
.attr("x2", function(d) {
var bbox = this.parentNode.getBBox();
return bbox.width;
})
.attr("y2", height + 50);
/* Styles go here */
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.bar {
fill: steelblue;
}
.x.axis path {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<script data-require="d3#3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Hello Plunker!</h1>
</body>
</html>

D3js: scale an axis on every bar chart

I'm building a d3js chart with horizontal bars and an axis on every bar.
Here is the jsfiddle http://jsfiddle.net/juri33/r5tkL8L1/
Now the scaling is done by this function
xScale.domain([0, d3.max(data, function(d) {
return d.initvalue * 2;
})]);
I would like to scale on every bar with different values -> every bar should get an another axis.
How can i do this? Any ideas?
Here's a quick fix which scales each axis separately:
// an array of scales
// that's 5% larger then the data is representing
var xs = data.map(function(d,i){
return d3.scale
.linear()
.range([0, width])
.domain([0, d.restlifetime + (d.restlifetime * 0.05)]);
});
// set width with appropriate scale
bar.append("rect")
.attr("width", function(d,i) {
return xs[i](d.restlifetime);
})
.attr("height", barHeight - 1);
// draw an axis for each scale
bar.append("g")
.attr("class", "x axis")
.attr("transform", function(d, i) {
return "translate(0, " + scaleOffset + ")";
})
.each(function(d,i){
d3.select(this)
.call(d3.svg.axis()
.scale(xs[i])
.orient("bottom"));
});
Full code:
var margin = {
top: 50,
right: 50,
bottom: 50,
left: 50
},
width = 500 - margin.left - margin.right,
barHeight = 20,
barOffset = 30,
scaleOffset = 19;
var data = [{
bearingname: "B1",
restlifetime: 1000
}, {
bearingname: "B2",
restlifetime: 100
}, {
bearingname: "B3",
restlifetime: 400
}, {
bearingname: "B4",
restlifetime: 300
}];
var x = d3.scale.linear()
.range([0, width]);
var chart = d3.select(".chart")
.attr("width", width + margin.left + margin.right + 300)
.attr("height", function(d, i) {
return (barHeight + barOffset) * data.length + margin.top + margin.bottom;
})
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var xs = data.map(function(d,i){
return d3.scale
.linear()
.range([0, width])
.domain([0, d.restlifetime + (d.restlifetime * 0.05)]);
});
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) {
return "translate(0," + i * (barHeight + barOffset) + ")";
});
bar.append("rect")
.attr("width", function(d,i) {
return xs[i](d.restlifetime);
})
.attr("height", barHeight - 1);
bar.append("g")
.attr("class", "x axis")
.attr("transform", function(d, i) {
return "translate(0, " + scaleOffset + ")";
})
.each(function(d,i){
d3.select(this)
.call(d3.svg.axis()
.scale(xs[i])
.orient("bottom"));
});
bar.append("text")
.attr("x", function(d,i) {
return xs[i](d.restlifetime) - 3;
})
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) {
return d.restlifetime + " h";
});
bar.append("text")
.attr("x", 520)
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.style("fill", "black")
.text(function(d) {
return d.bearingname;
});
bar.append("text")
.attr("x", 600)
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.style("fill", "black")
.html("S 0, min");
.chart rect {
fill: green;
}
.chart text {
fill: white;
font: 10px sans-serif;
text-anchor: end;
}
.bar text {
fill: black;
}
.axis text {
font: 10px sans-serif;
fill: black;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg class="chart"></svg>

I want to change the domain in th below code in d3

var margin = {top: 20, right: 30, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
padding = 0.3;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], padding);
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")
.tickFormat(function(d) { return percentage(d); })
var tooltip = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0)
.attr("align","middle");
var chart = d3.select(".chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
data = [
{"name":"Product Revenue","value":420000},
{"name":"Services Revenue","value":210000},
{"name":"Employee Revenue","value":190000},
{"name":"Fixed Costs","value":-170000},
{"name":"Variable Costs","value":-140000}
];
//function to find all the positive values
var positive_val = data.filter(function(d) { return d.value > 0; });
console.log(JSON.stringify(positive_val));
//function to calculate the sum of all the positive values
var maxSum = positive_val.reduce(function(sum, d) {
return sum + d.value;
}, 0);
console.log("The maximum sum is "+maxSum);
//to calculate the new Domain by adding 120
var yaxisRange=maxSum+120;
console.log("The y axis sum is "+yaxisRange);
var newDomain=percentage(yaxisRange);
console.log(newDomain);
var newDomain = newDomain.replace(/[!##$%^&*]/g, "");
console.log(newDomain);
// Transform data (i.e., finding cumulative values and total)
var cumulative = 0;
for (var i = 0; i < data.length; i++) {
data[i].start = cumulative;
cumulative += data[i].value;
data[i].end = cumulative;
data[i].class = ( data[i].value >= 0 ) ? 'positive' : 'negative'
}
data.push({
name: 'Total',
end: cumulative,
start: 0,
class: 'total',
value: cumulative
});
x.domain(data.map(function(d) { return d.name; }));
y.domain([0, d3.max(data, function(d) { return d.end; })]);
//WHen i try to use this as my new domain,the bar increase the height
//y.domain([0,newDomain]);
debugger;
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
chart.append("g")
.attr("class", "y axis")
.call(yAxis);
var bar = chart.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("class", function(d) { return "bar " + d.class })
.attr("transform", function(d) { return "translate(" + x(d.name) + ",0)"; });
bar.append("rect")
//.attr("y", function(d) { return y(d.value); })
.attr("y", function(d) { return y( Math.max(d.start, d.end) ); })
.attr("height", function(d) { return Math.abs( y(d.start) - y(d.end) ); })
//function to draw the tooltip
.attr("width", x.rangeBand()).on("mouseover", function(d) {
// to find the parent node,to calculate the x position
var parentG = d3.select(this.parentNode);
var barPos = parseFloat(parentG.attr('transform').split("(")[1]);
var xPosition = barPos+x.rangeBand()/2;
//to find the y position
var yPosition = parseFloat(d3.select(this).attr("y"))+ Math.abs( y(d.start) - y(d.end))/2;
tooltip.transition()
.duration(200)
.style("opacity", .9);
tooltip.html(d.name + "<br/>" + percentage(d.value))
.style("left", xPosition + "px")
.style("top", yPosition + "px");
}).on("mouseout", function(d) {
tooltip.transition()
.duration(500)
.style("opacity", 0);
});
bar.append("text")
.attr("x", x.rangeBand() / 2)
.attr("y", function(d) { return y(d.end) + 5; })
.attr("dy", function(d) { return ((d.class=='negative') ? '-' : '') + ".75em" })
.text(function(d) { return percentage(d.end - d.start);});
bar.filter(function(d) { return d.class != "total" }).append("line")
.attr("class", "connector")
.attr("x1", x.rangeBand() + 5 )
.attr("y1", function(d) { return y(d.end) } )
.attr("x2", x.rangeBand() / ( 1 - padding) - 5 )
.attr("y2", function(d) { return y(d.end) } )
function type(d) {
d.value = +d.value;
return d;
}
function percentage(n) {
n = Math.round(n);
var result = n;
if (Math.abs(n) > 100) {
result = Math.round(n/100) + '%';
}
return result;
}
-Here is the updated fiddle http://jsfiddle.net/7mkq4k8k/21/
-I want to make the yaxis label increase .for eg 9000,9500.I have calculated the newDomian.
-If i try to add this domain,my chart doesnt get drawn properly.The height of the bars increase ,and the due to this the rest of the bars are not drawn.Please help me in this issue.
So the chart you initially draw is based on this domain :
y.domain([0, d3.max(data, function (d) {
return d.end;
})]);
Try to console.log(d3.max(data, function (d) {return d.end;})) and you will find it returns 820000, which is the maximum of your cumulative calculation. That means your chart is drawn with a domain from 0 to 820000.
Now let's talk about your newDomain. You're taking the percentage of your maxSum, which means your newDomain is equal to 8201. So now you're trying to draw your chart from 0 to 8201.
But your bars height is calculated like this :
Math.abs(y(d.start) - y(d.end)), which means you are calculating ranges from y(0) to y(820000) (d.end is max equal to 820000).
y(820000) doesn't fit, as you specified with your domain that it could max go to y(8201). That's why your bars are reaching over the very top of your chart, because the domain you're giving doesn't correspond the numbers inside :
y(this number is too big and doesn't fit because it is not between 0 and newDomain).
How to solve this ?
You define your domain correctly, removing the percentage line
//function to calculate the sum of all the positive values
var maxSum = positive_val.reduce(function (sum, d) {
return sum + d.value;
}, 0);
console.log("The maximum sum is " + maxSum);
//to calculate the new Domain by adding 520000 (big number to show you it works)
var newDomain = maxSum + 520000;
console.log(newDomain); //1340000
y.domain([0,newDomain]);
Working snippet below :
var margin = {
top: 20,
right: 30,
bottom: 30,
left: 40
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
padding = 0.3;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], padding);
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")
.tickFormat(function (d) {
return percentage(d);
})
var tooltip = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0)
.attr("align", "middle");
var chart = d3.select(".chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
data = [{
"name": "Product Revenue",
"value": 420000
}, {
"name": "Services Revenue",
"value": 210000
}, {
"name": "Employee Revenue",
"value": 190000
}, {
"name": "Fixed Costs",
"value": -170000
}, {
"name": "Variable Costs",
"value": -140000
}
];
//function to find all the positive values
var positive_val = data.filter(function (d) {
return d.value > 0;
});
console.log(JSON.stringify(positive_val));
//function to calculate the sum of all the positive values
var maxSum = positive_val.reduce(function (sum, d) {
return sum + d.value;
}, 0);
console.log("The maximum sum is " + maxSum);
//to calculate the new Domain by adding 120
var newDomain = maxSum + 520000;
console.log(newDomain);
// Transform data (i.e., finding cumulative values and total)
var cumulative = 0;
for (var i = 0; i < data.length; i++) {
data[i].start = cumulative;
cumulative += data[i].value;
data[i].end = cumulative;
data[i].class = (data[i].value >= 0) ? 'positive' : 'negative'
}
data.push({
name: 'Total',
end: cumulative,
start: 0,
class: 'total',
value: cumulative
});
x.domain(data.map(function (d) {
return d.name;
}));
console.log(d3.max(data, function (d) {
return d.end;
}));
/*y.domain([0, d3.max(data, function (d) {
return d.end;
})]);*/
//WHen i try to use this as my new domain,the bar increase the height
y.domain([0,newDomain]);
debugger;
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
chart.append("g")
.attr("class", "y axis")
.call(yAxis);
var bar = chart.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("class", function (d) {
return "bar " + d.class
})
.attr("transform", function (d) {
return "translate(" + x(d.name) + ",0)";
});
bar.append("rect")
//.attr("y", function(d) { return y(d.value); })
.attr("y", function (d) {
return y(Math.max(d.start, d.end));
})
.attr("height", function (d) {
return Math.abs(y(d.start) - y(d.end));
})
//function to draw the tooltip
.attr("width", x.rangeBand()).on("mouseover", function (d) {
// to find the parent node,to calculate the x position
var parentG = d3.select(this.parentNode);
var barPos = parseFloat(parentG.attr('transform').split("(")[1]);
var xPosition = barPos + x.rangeBand() / 2;
//to find the y position
var yPosition = parseFloat(d3.select(this).attr("y")) + Math.abs(y(d.start) - y(d.end)) / 2;
tooltip.transition()
.duration(200)
.style("opacity", .9);
tooltip.html(d.name + "<br/>" + percentage(d.value))
.style("left", xPosition + "px")
.style("top", yPosition + "px");
}).on("mouseout", function (d) {
tooltip.transition()
.duration(500)
.style("opacity", 0);
});
bar.append("text")
.attr("x", x.rangeBand() / 2)
.attr("y", function (d) {
return y(d.end) + 5;
})
.attr("dy", function (d) {
return ((d.class == 'negative') ? '-' : '') + ".75em"
})
.text(function (d) {
return percentage(d.end - d.start);
});
bar.filter(function (d) {
return d.class != "total"
}).append("line")
.attr("class", "connector")
.attr("x1", x.rangeBand() + 5)
.attr("y1", function (d) {
return y(d.end)
})
.attr("x2", x.rangeBand() / (1 - padding) - 5)
.attr("y2", function (d) {
return y(d.end)
})
function type(d) {
d.value = +d.value;
return d;
}
function percentage(n) {
n = Math.round(n);
var result = n;
if (Math.abs(n) > 100) {
result = Math.round(n / 100) + '%';
}
return result;
}
.bar.total rect {
fill: steelblue;
}
.bar:hover rect {
fill:orange;
}
.bar.positive rect {
fill: darkolivegreen;
}
.bar:hover rect {
fill:orange;
}
.bar.negative rect {
fill: crimson;
}
.bar:hover rect {
fill:orange;
}
.bar line.connector {
stroke: grey;
stroke-dasharray: 3;
}
.bar text {
fill: white;
font: 12px sans-serif;
text-anchor: middle;
}
.axis text {
font: 10px sans-serif;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
div.tooltip {
position:absolute;
text-align: center;
padding: 2px;
font: 12px sans-serif;
background: #33CC00;
border: 0px;
border-radius: 8px;
pointer-events: none;
width: 90px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg class="chart"></svg>
Hope this helps !

make the series d3 graph chart

I trying to display a d3 linechart. I've a problem - I cannot stop the date from repeating. How can I stop the date keep repeating? I only want to show two columns(17/12/2013 and 18/12/2013) based on the JSON data reflected below. Or what do I need to do so the first tickmark would show 17/12/2013 and the last one would show 18/12/2013?
[
{
"key": "Excited",
"values": [ [1387212490000, 0], [1387298890000 , 10] ]
},
{
"key": "Sad",
"values": [ [1387212490000, 20], [1387298890000 , 50] ]
},
{
"key": "Angry",
"values": [ [1387212490000, 30], [1387298890000 , 30] ]
},
{
"key": "Happy",
"values": [ [1387212490000, 40], [1387298890000 , 70] ]
}
]
Below is the JS script
$(document).ready(function() {
d3.json('sales.json', function(data) {
nv.addGraph(function() {
var chart = nv.models.lineChart().x(function(d) {
return d[0]
}).y(function(d) {
return d[1]
}).color(d3.scale.category10().range())
.useInteractiveGuideline(true);
chart.xAxis.tickFormat(function(d) {
return d3.time.format('%d/%m/%Y')(new Date(d))
});
//chart.xScale(d3.time.scale());
d3.select('#nvd3 svg').datum(data).transition().duration(500).call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
});
});
You didn't show enough code so it may be difficult to debug...
Anyway, try this and I'm working on an example to prove it...
chart.xAxis
.tickFormat(function(d) {
return d3.time.format('%d/%m/%Y')(new Date(d))
})
.ticks(d3.time.days, 1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
var margin = {top: 20, right: 40, bottom: 30, left: 20},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
barWidth = Math.floor(width / 19) - 1;
var x = d3.scale.linear()
.range([barWidth / 2, width - barWidth / 2]);
var y = d3.scale.linear()
.range([height, 0]);
var yAxis = d3.svg.axis()
.scale(y)
.orient("right")
.tickSize(-width)
.tickFormat(function(d) { return Math.round(d / 1e6) + "M"; });
// An SVG element with a bottom-right origin.
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 + ")");
// A sliding container to hold the bars by birthyear.
var birthyears = svg.append("g")
.attr("class", "birthyears");
// A label for the current year.
var title = svg.append("text")
.attr("class", "title")
.attr("dy", ".71em")
.text(2000);
d3.csv("population.csv", function(error, data) {
// Convert strings to numbers.
data.forEach(function(d) {
d.people = +d.people;
d.year = +d.year;
d.age = +d.age;
});
// Compute the extent of the data set in age and years.
var age1 = d3.max(data, function(d) { return d.age; }),
year0 = d3.min(data, function(d) { return d.year; }),
year1 = d3.max(data, function(d) { return d.year; }),
year = year1;
// Update the scale domains.
x.domain([year1 - age1, year1]);
y.domain([0, d3.max(data, function(d) { return d.people; })]);
// Produce a map from year and birthyear to [male, female].
data = d3.nest()
.key(function(d) { return d.year; })
.key(function(d) { return d.year - d.age; })
.rollup(function(v) { return v.map(function(d) { return d.people; }); })
.map(data);
// Add an axis to show the population values.
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + width + ",0)")
.call(yAxis)
.selectAll("g")
.filter(function(value) { return !value; })
.classed("zero", true);
// Add labeled rects for each birthyear (so that no enter or exit is required).
var birthyear = birthyears.selectAll(".birthyear")
.data(d3.range(year0 - age1, year1 + 1, 5))
.enter().append("g")
.attr("class", "birthyear")
.attr("transform", function(birthyear) { return "translate(" + x(birthyear) + ",0)"; });
birthyear.selectAll("rect")
.data(function(birthyear) { return data[year][birthyear] || [0, 0]; })
.enter().append("rect")
.attr("x", -barWidth / 2)
.attr("width", barWidth)
.attr("y", y)
.attr("height", function(value) { return height - y(value); });
// Add labels to show birthyear.
birthyear.append("text")
.attr("y", height - 4)
.text(function(birthyear) { return birthyear; });
// Add labels to show age (separate; not animated).
svg.selectAll(".age")
.data(d3.range(0, age1 + 1, 5))
.enter().append("text")
.attr("class", "age")
.attr("x", function(age) { return x(year - age); })
.attr("y", height + 4)
.attr("dy", ".71em")
.text(function(age) { return age; });
// Allow the arrow keys to change the displayed year.
window.focus();
d3.select(window).on("keydown", function() {
switch (d3.event.keyCode) {
case 37: year = Math.max(year0, year - 10); break;
case 39: year = Math.min(year1, year + 10); break;
}
update();
});
function update() {
if (!(year in data)) return;
title.text(year);
birthyears.transition()
.duration(750)
.attr("transform", "translate(" + (x(year1) - x(year)) + ",0)");
birthyear.selectAll("rect")
.data(function(birthyear) { return data[year][birthyear] || [0, 0]; })
.transition()
.duration(750)
.attr("y", y)
.attr("height", function(value) { return height - y(value); });
}
});
svg {
font: 10px sans-serif;
}
.y.axis path {
display: none;
}
.y.axis line {
stroke: #fff;
stroke-opacity: .2;
shape-rendering: crispEdges;
}
.y.axis .zero line {
stroke: #000;
stroke-opacity: 1;
}
.title {
font: 300 78px Helvetica Neue;
fill: #666;
}
.birthyear,
.age {
text-anchor: middle;
}
.birthyear {
fill: #fff;
}
rect {
fill-opacity: .6;
fill: #e377c2;
}
rect:first-child {
fill: #1f77b4;
}

Categories

Resources