Skip to content

Instantly share code, notes, and snippets.

@avrasgoldman
Last active February 14, 2018 04:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avrasgoldman/2667613aba6d675d85d11a8e644964f9 to your computer and use it in GitHub Desktop.
Save avrasgoldman/2667613aba6d675d85d11a8e644964f9 to your computer and use it in GitHub Desktop.
co2 in fuel
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.min.js"></script>
<style>
.tip {
line-height: 1;
padding: 6px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
border-radius: 4px;
font-size: 12px;
font-family: Lato;
}
/* Creates a small triangle extender for the tooltip */
.tip:after {
box-sizing: border-box;
display: inline;
font-size: 10px;
width: 100%;
line-height: 1;
color: rgba(0, 0, 0, 0.8);
content: "\25BC";
position: absolute;
text-align: center;
}
/* Style northward tooltips specifically */
.tip.n:after {
margin: -2px 0 0 0;
top: 100%;
left: 0;
}
.xAxis{
stroke-dasharray: ;
}
.group-label {
font-weight: bold;
text-anchor: end;
}
</style>
</head>
<body>
<form>
<label>
<input type="radio" name="mode" value="stacked"> Stacked
</label>
<label>
<input type="radio" name="mode" value="multiples" checked>Multiples
</label>
</form>
<script>
//Firstly, you need to hold off assigning the y scales' range and domains until you have the data loaded, as the bandwidth won't be correct. Secondly, the keys for the vehicles and fuel types were mixed up. and then, once that was sorted - the y positions for the groups and rects needed tweaking to account for the bandwidth, and the d[0] and d[1]. You will need to update the part which assigns the max value to y linear scale, as it should be max value for a particular vehicle+fuel type, not d.total, as this scale needs to span the y0.bandwidth, not the whole height of the chart. hope this makes sense//
var margin = { top: 40, right: 40, bottom: 40, left: 40};
var width = 960 - margin.left - margin.right;
var height = 500 - 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)
.attr('transform', 'translate(' + margin.left +', ' + margin.top + ')');
var gSVG = svg.append('g')
.attr('class', 'svg');
var x = d3.scaleBand()
.rangeRound([0, width])
.paddingInner(0.3)
.align(0.1);
var y0 = d3.scaleBand()
.rangeRound([height, 0]);
var y = d3.scaleLinear();
var zScale = d3.scaleOrdinal()
.range(["DarkGoldenRod ", "GoldenRod", "OliveDrab", "YellowGreen", "LimeGreen"]);
var data = data;
// var allVehicleTypeKeys = ["diesel", "B20", "gasoline", "B100", "CNG"];
d3.csv("The Impact of Fuel.csv", function(d, i, columns) {
for (i = 1, t = 0; i < columns.length; ++i) t += d[columns[i]] = +d[columns[i]];
d.total = t;
return d;
}, function(error, data) {
if (error) throw error;
var allFuelTypeKeys = data.columns.slice(1);
data.sort(function(a, b) { return b.total - a.total; });
x.domain(data.map(function(d) {return d.vehicleType; }));
zScale.domain(allFuelTypeKeys);
var stack = d3.stack()
.keys(allFuelTypeKeys)
(data);
y0.domain(stack.map(function(d) { return d.key; }))
y.range([y0.bandwidth(), 0])
.domain([0, 1800]).nice();
// .domain([0, d3.max(data, function(d) { return d.total; })]).nice();
var tip = d3.tip()
.attr("class", "tip")
.offset([-8, 0])
.html(function(d) { return d[1]-d[0];})
svg.call( tip)
var group = gSVG.selectAll('g')
.data(stack)
.enter().append('g')
.attr('class', 'group')
.attr("fill", function(d) { return zScale(d.key); })
.attr("transform", "translate(69," + height + ")")
//labels
group.append("text")
.attr("class", "group-label")
.attr("x", -8)
.attr("y", function(d) {return y(d[0][0]) - y0.bandwidth() - (y(d[0][0]) - y(d[0][1]))/2; })
.attr("dy", ".35em")
.text(function(d) {return d.key})
group.selectAll('rect')
.data(function(d) { return d;})
.enter().append("rect")
.attr("x", function(d) { return x(d.data.vehicleType)})
.attr("y", function(d) { return y(d[1]) - y0.bandwidth(); })
.attr("height", function(d) { return y(d[0]) - y(d[1]) })
.attr("width", x.bandwidth())
.style("stroke", "white")
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
//append x axis
svg.append("g")
.attr("class", "xAxis")
.attr("transform", "translate(69," + height + ")")
.call(d3.axisBottom(x));
var title = svg.append("text")
.text("POUNDS CO2")
.attr("transform", "translate("+[margin.right *10, margin.top]+")")
.attr("text-anchor","center")
.style("font-size", 28)
.style("font-family", "Lato")
.style("fill", "black")
.style("opacity", .6);
d3.selectAll("input")
.on("change", change);
function change() {
if (this.value === "stacked") transitionStacked();
else transitionMultiples ();
}
d3.select("input[value=\"stacked\"]")
.property("checked", true)
function transitionMultiples() {
var t = svg.transition()
.duration(750),
g = t.selectAll(".group")
.attr("transform", function(d) { return "translate(69," + y0(d.key) + ")"; });
t.selectAll("rect")
.attr("y", function(d) {return y0.bandwidth() + (y(d[1]) - y(d[0])); });
g.select(".group-label")
.attr("y", function(d) { console.log(d[1][1]); return y(d[1][1]) / 1000; })
}
function transitionStacked() {
var t = svg.transition()
.duration(750),
g=t.selectAll(".group")
.attr("transform", "translate(69," + height + ")");
g.selectAll("rect")
.attr("y", function(d) { return y(d[1]) - y0.bandwidth(); });
g.select(".group-label")
.attr("y", function(d) { return y(d[0][0]) - y0.bandwidth() - (y(d[0][0]) - y(d[0][1]))/2; })
}
});
</script>
</body>
vehicleType diesel B20 gasoline B100 CNG
generator 1000 1000 1000 1000 500
hybrid car 300 300 200 200 200
car 400 400 400 400 300
hybrid SUV 300 300 300 300 200
van, pickup, SUV 600 600 500 500 400
truck (<18 wheels) 1400 1400 1200 1300 1000
18 wheeler 1800 1700 1500 1000 1200
bus 1700 1700 1500 1600 1200
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment