JSFiddle - React, Tailwind, and code Playground
by rahilwazir
HTML
<div id="tooltip" class="hidden">
<p><span id="value">100</span></p>
</div>
<div id="chart" class="stackedchart"></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
CSS
body {
font: 10px sans-serif;
background: #272a2f;
}
.axis path,
.axis line {
fill: none;
stroke: #fff;
shape-rendering: crispEdges;
}
text{
fill: #fff;
}
.bar {
fill: steelblue;
}
.x.axis path {
/*display: none;*/
}
.legend{
position: absolute;
top: 0;
right:0;
}
.stackedchart{
position: relative;
width: 600px;
height: 700px;
}
#tooltip {
position: absolute;
width: auto;
height: auto;
padding: 5px;
background-color: white;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
-webkit-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
-moz-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
pointer-events: none;
z-index:1;
}
#tooltip.hidden {
display: none;
}
#tooltip p {
margin: 0;
font-family: sans-serif;
font-size: 16px;
line-height: 20px;
}
JavaScript
var stackedChart = {
init: function(){
var that = this;
var margin = {top: 20, right: 20, bottom: 90, left: 40},
width = 240 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.rangeRound([height, 0]);
var color = d3.scale.ordinal()
.range(["#20b2aa", "#fa8072", "#87ceeb", "#daa520", "#00bfff", "#dc143c", "#87cefa", "#90ee90", "#add8e6", "#d3d3d3"]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
//.tickFormat(d3.format(".2s"));
var svg = d3.select("#chart")
.append("svg")
.attr("class", "chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var legendholder = d3.select("#chart")
.append("svg")
.attr("class", "legend")
.attr("width", "300")
.attr("height", "300")
that.getRawData(function(data){
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "Label"; }));
data.forEach(function(d) {
var y0 = 0;
d.ages = color.domain().map(function(name) {
return {name: name, hours: d[name], y0: y0, y1: y0 += +d[name]};
});
d.total = d.ages[d.ages.length - 1].y1;
});
//data.sort(function(a, b) { return b.total - a.total; });
x.domain(data.map(function(d) { return d.Label; }));
y.domain([0, d3.max(data, function(d) { return d.total; })]);
var chart = svg.append("g")
.attr("class", "chart")
.attr("width", 500) ;
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
chart.append("g")
.attr("class", "y axis")
...