Skip to content

Instantly share code, notes, and snippets.

@GerardoFurtado
Created December 6, 2015 05:20
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 GerardoFurtado/c4debeb0f7c8bec1715c to your computer and use it in GitHub Desktop.
Save GerardoFurtado/c4debeb0f7c8bec1715c to your computer and use it in GitHub Desktop.
CO2 emissions

Here I’m cheating using D3: I tried to use “object constancy”, following tutorials and examples but, despite the bars entering and exiting nicely, my x.Axis labels were not behaving accordingly. Then, I realized that I could simply create a huge xScale range, way bigger than the SVG. There are no “enter”, “update” and “exit” functions here: this is a very plain and simple bar chart.

countryname countrycode emissionpercap totalemission
Aruba ABW 23.92 2439
Andorra AND 5.97 491
Afghanistan AFG 0.43 12251
Angola AGO 1.35 29710
Albania ALB 1.61 4668
United Arab Emirates ARE 20.43 178484
Argentina ARG 4.56 190035
Armenia ARM 1.67 4961
Antigua and Barbuda ATG 5.82 513
Australia AUS 16.52 369040
Austria AUT 7.77 65203
Azerbaijan AZE 3.65 33458
Burundi BDI 0.02 209
Belgium BEL 8.85 97766
Benin BEN 0.51 4987
Burkina Faso BFA 0.12 1933
Bangladesh BGD 0.37 57070
Bulgaria BGR 6.71 49339
Bahrain BHR 17.95 23439
Bahamas BHS 5.20 1907
Bosnia and Herzegovina BIH 6.20 23747
Belarus BLR 6.68 63303
Belize BLZ 1.67 550
Bermuda BMU 6.08 392
Bolivia BOL 1.60 16120
Brazil BRA 2.19 439413
Barbados BRB 5.58 1566
Brunei Darussalam BRN 24.39 9743
Bhutan BTN 0.77 561
Botswana BWA 2.32 4855
Central African Republic CAF 0.06 286
Canada CAN 14.14 485463
Switzerland CHE 4.63 36597
Chile CHL 4.62 79409
China CHN 6.71 9019518
Cote d'Ivoire CIV 0.31 6447
Cameroon CMR 0.27 5662
Congo COG 0.54 2248
Colombia COL 1.56 72423
Comoros COM 0.22 158
Cabo Verde CPV 0.86 425
Costa Rica CRI 1.70 7844
Cuba CUB 3.17 35922
Cayman Islands CYM 10.30 583
Cyprus CYP 6.74 7521
Czech Republic CZE 10.43 109486
Germany DEU 8.92 729458
Djibouti DJI 0.56 473
Dominica DMA 1.75 125
Denmark DNK 7.25 40377
Dominican Republic DOM 2.18 21888
Algeria DZA 3.32 121755
Ecuador ECU 2.35 35728
Egypt EGY 2.64 220790
Eritrea ERI 0.11 521
Spain ESP 5.79 270676
Estonia EST 14.05 18650
Ethiopia ETH 0.08 7543
Finland FIN 10.16 54767
Fiji FJI 1.42 1236
France FRA 5.19 338805
Faeroe Islands FRO 11.72 568
Micronesia FSM 1.24 128
Gabon GAB 1.42 2237
United Kingdom GBR 7.09 448236
Georgia GEO 1.77 7932
Ghana GHA 0.40 10081
Guinea GIN 0.23 2596
Gambia GMB 0.24 422
Guinea-Bissau GNB 0.15 246
Equatorial Guinea GNQ 8.91 6689
Greece GRC 7.56 84048
Grenada GRD 2.41 253
Greenland GRL 12.44 708
Guatemala GTM 0.75 11258
Guyana GUY 2.36 1782
Honduras HND 1.10 8412
Croatia HRV 4.80 20554
Haiti HTI 0.22 2211
Hungary HUN 4.86 48492
Indonesia IDN 2.30 563985
India IND 1.66 2074345
Ireland IRL 7.88 36069
Iran IRN 7.80 586599
Iraq IRQ 4.20 133655
Iceland ISL 5.90 1881
Israel ISR 8.95 69523
Italy ITA 6.70 397994
Jamaica JAM 2.87 7756
Jordan JOR 3.60 22259
Japan JPN 9.29 1187657
Kazakhstan KAZ 15.81 261761
Kenya KEN 0.33 13568
Kyrgyz Republic KGZ 1.20 6615
Cambodia KHM 0.31 4496
Kiribati KIR 0.60 62
St. Kitts and Nevis KNA 5.05 268
South Korea KOR 11.84 589426
Kuwait KWT 28.10 91030
Lao PDR LAO 0.19 1203
Lebanon LBN 4.67 20488
Liberia LBR 0.22 891
Libya LBY 6.20 39021
St. Lucia LCA 2.27 407
Liechtenstein LIE 1.41 51
Sri Lanka LKA 0.73 15233
Lesotho LSO 1.08 2200
Lithuania LTU 4.54 13740
Luxembourg LUX 20.90 10832
Latvia LVA 3.79 7800
Morocco MAR 1.74 56538
Moldova MDA 1.40 4980
Madagascar MDG 0.11 2450
Maldives MDV 3.26 1104
Mexico MEX 3.88 466549
Marshall Islands MHL 1.95 103
Macedonia MKD 4.52 9336
Mali MLI 0.08 1250
Malta MLT 6.03 2512
Myanmar MMR 0.20 10440
Montenegro MNE 4.15 2571
Mongolia MNG 6.92 19079
Mozambique MOZ 0.13 3282
Mauritania MRT 0.63 2310
Mauritius MUS 3.13 3916
Malawi MWI 0.08 1206
Malaysia MYS 7.90 225693
Namibia NAM 1.24 2776
New Caledonia NCL 15.17 3854
Niger NER 0.08 1423
Nigeria NGA 0.54 88026
Nicaragua NIC 0.84 4899
Netherlands NLD 10.06 168007
Norway NOR 9.19 45533
Nepal NPL 0.16 4334
New Zealand NZL 7.12 31232
Oman OMN 20.20 64855
Pakistan PAK 0.94 163453
Panama PAN 2.63 9666
Peru PER 1.78 53069
Philippines PHL 0.87 82012
Palau PLW 10.86 224
Papua New Guinea PNG 0.75 5229
Poland POL 8.34 317287
North Korea PRK 2.99 73578
Portugal PRT 4.71 49725
Paraguay PRY 0.84 5299
Pacific island small states PSS 1.10 2448
French Polynesia PYF 3.17 858
Qatar QAT 44.02 83875
Romania ROU 4.21 84832
Russian Federation RUS 12.65 1808073
Rwanda RWA 0.06 664
Saudi Arabia SAU 18.07 520278
Sudan SDN 0.35 16579
Senegal SEN 0.59 7858
Singapore SGP 4.32 22394
Solomon Islands SLB 0.37 198
Sierra Leone SLE 0.15 898
El Salvador SLV 1.10 6685
Somalia SOM 0.06 576
Serbia SRB 6.80 49185
Sao Tome and Principe STP 0.59 103
Suriname SUR 3.65 1911
Slovak Republic SVK 6.37 34374
Slovenia SVN 7.50 15405
Sweden SWE 5.52 52145
Swaziland SWZ 0.86 1049
Seychelles SYC 6.84 598
Syrian Arab Republic SYR 2.74 57671
Turks and Caicos Islands TCA 6.01 191
Chad TCD 0.04 539
Togo TGO 0.32 2098
Thailand THA 4.53 303371
Tajikistan TJK 0.36 2783
Turkmenistan TKM 12.18 62218
Timor-Leste TLS 0.16 183
Tonga TON 0.98 103
Trinidad and Tobago TTO 37.14 49574
Tunisia TUN 2.40 25643
Turkey TUR 4.38 320840
Tanzania TZA 0.15 7301
Uganda UGA 0.11 3799
Ukraine UKR 6.26 286228
Uruguay URY 2.30 7774
United States USA 17.02 5305570
Uzbekistan UZB 3.91 114861
St. Vincent and the Grenadines VCT 2.18 238
Venezuela VEN 6.42 188817
Vietnam VNM 1.97 173211
Vanuatu VUT 0.59 143
Samoa WSM 1.25 235
Yemen YEM 0.92 22295
South Africa ZAF 9.26 477242
Zambia ZMB 0.21 3047
Zimbabwe ZWE 0.69 9861
<!DOCTYPE html>
<html lang="en">
<head>
<link href='https://fonts.googleapis.com/css?family=PT+Serif' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=PT+Sans' rel='stylesheet' type='text/css'>
<meta charset="utf-8">
<title>CO2 Emissions</title>
<style type="text/css">
body {
padding-left: 100px;
background-color: white;
font-family: 'PT Serif', serif;
}
h1 {
font-weight: 400;
color: black;
font-family: 'PT Sans', sans-serif;
font-size: 60px;
margin-bottom: 10px;
margin-top: 30px;
padding-left: 90px;
}
p {
font-size: 18px;
width: 910px;
margin-top: 10px;
padding-left: 90px;
margin-bottom: 10px;
}
.footer {
font-size: 14px;
margin-top: 0px;
}
.btn-group {
padding-left: 90px;
}
.button {
border-top: 1px solid #ffffff;
background: #ffffff;
background: -webkit-gradient(linear, left top, left bottom, from(#d4d4d4), to(#ffffff));
background: -webkit-linear-gradient(top, #d4d4d4, #ffffff);
background: -moz-linear-gradient(top, #d4d4d4, #ffffff);
background: -ms-linear-gradient(top, #d4d4d4, #ffffff);
background: -o-linear-gradient(top, #d4d4d4, #ffffff);
padding: 5px 10px;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
/* -webkit-box-shadow: rgba(0,0,0,1) 0 1px 0;
-moz-box-shadow: rgba(0,0,0,1) 0 1px 0;
box-shadow: rgba(0,0,0,1) 0 1px 0;*/
/* text-shadow: rgba(0,0,0,.4) 0 1px 0;*/
color: #262426;
font-size: 14px;
font-family: "PT Sans";
text-decoration: none;
vertical-align: middle;
margin-right: 20px;
margin-bottom: 10px;
margin-top: 10px;
}
.button:hover {
border-top-color: #bfc4c7;
background: #cfd4d7;
color: #000000;
cursor: pointer;
}
.button:active {
border-top-color: #ffffff;
background: #ffffff;
}
.button:focus {
outline: 0;
}
svg {
background-color: white;
}
.bar {
fill: darkslategray;
}
.bar:hover {
fill: saddlebrown;
}
.value {
fill: white;
}
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 10px;
}
.y.axis path,
.y.axis line {
stroke: #fff;
stroke-dasharray: 1,2;
opacity: 1;
}
div.tooltip {
position: absolute;
text-align: center;
white-space: normal;
padding: 2px;
font-size: 14px;
background: ivory;
border: 1px solid gray;
border-radius: 4px;
pointer-events: none;
cursor: none;
}
</style>
<script type="text/javascript" src="http://d3js.org/d3.v3.js"></script>
</head>
<body>
<h1>CO<sub>2</sub> Emissions</h1>
<p>This chart shows the top 35 countries, out of 196, by annual emissions of CO<sub>2</sub> (in kilotonnes, or 10<sup>9</sup> kg) as well as by annual per capita emissions of CO<sub>2</sub> (in metric tons). Hover to see more detailed information. Data for 2011.</p>
<div class="btn-group" data-toggle="buttons-radio">
<button type="button" id="total" class="button">Total emissions</button>
<button type="button" id="percapita" class="button">Per capita emissions</button>
</div>
<div id="svganchor"></div>
<p>Source of the data: <a href="http://data.worldbank.org/indicator/EN.ATM.CO2E.PC">The World Bank</a>.</p>
<p class="footer">Created by Gerardo Furtado (and all the people whose code I copy-pasted).</p>
<script type="text/javascript">
var w = 1000;
var h = 500;
var padding = [ 20, 10, 20, 80 ]; //Top, right, bottom, left
//test excess
var xScale = d3.scale.ordinal()
.rangeRoundBands([ padding[3], 5190 ], 0.2);
var yScale = d3.scale.linear()
.range([ h - padding[2] - padding[0], 0 ]);
var xAxis = d3.svg.axis()
.scale(xScale)
.tickSize(0)
.tickPadding(8)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(yScale)
.innerTickSize(-(w))
.outerTickSize(0)
.orient("left");
var svg = d3.select("#svganchor")
.append("svg")
.attr("width", w)
.attr("height", h);
var formatnum = d3.format("0,000");
var tt = d3.select("#svganchor").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
d3.csv("co2emissions.csv", function(data){
yScale.domain([0, d3.max(data, function(d) {
return +d.totalemission;
})]);
var top = data.sort(function(a, b) {
return d3.descending(+a.totalemission, +b.totalemission);
});
xScale.domain(top.map(function(d) { return d.countrycode; } ));
var bars = svg.selectAll("rect")
.data(top)
.enter()
.append("rect");
bars.attr("y", h - padding[2])
.attr("x", function(d) {
return xScale(d.countrycode);
})
.attr("height", 0)
.attr("width", xScale.rangeBand())
.attr("class", "bar")
.attr("opacity", 1);
bars.transition()
.delay(function(d, i) {
return i * 50;
})
.duration(500)
.attr("y", function(d) {
return yScale(d.totalemission) + padding[2];
})
.attr("height", function(d) {
return (h - padding[0] - padding[2]) - yScale(d.totalemission);
});
bars.on("mousemove", function(d) {
tt.html(" <strong>" + d.countryname + "</strong> has a total CO<sub>2</sub> production <br> of <strong>" + formatnum(d.totalemission) + "</strong> kilotonnes")
.style('top', d3.event.pageY - 12 + 'px')
.style('left', d3.event.pageX + 25 + 'px')
.style("opacity", 0.9);
});
bars.on("mouseout", function(d) {
tt.style("opacity", 0);
});
//first button
d3.select("#total")
.on("click", function() {
var top = data.sort(function(a, b) {
return d3.descending(+a.totalemission, +b.totalemission);
});
yScale.domain([0, d3.max(data, function(d) {
return +d.totalemission;
})]);
xScale.domain(top.map(function(d) { return d.countrycode; } ));
//update
var barupdate = svg.selectAll("rect");
barupdate.attr("class", "bar")
.transition()
.duration(2000)
.attr("y", h - padding[2])
.attr("x", function(d) {
return xScale(d.countrycode);
})
.attr("width", xScale.rangeBand())
.attr("y", function(d) {
return yScale(d.totalemission) + padding[2];
})
.attr("height", function(d) {
return (h - padding[0] - padding[2]) - yScale(d.totalemission);
});
d3.selectAll(".bar").on("mousemove", function(d) {
tt.html(" <strong>" + d.countryname + "</strong> has a total CO<sub>2</sub> production <br> of <strong>" + formatnum(d.totalemission) + "</strong> kilotonnes")
.style('top', d3.event.pageY - 12 + 'px')
.style('left', d3.event.pageX + 25 + 'px')
.style("opacity", 0.9);
});
d3.selectAll(".bar").on("mouseout", function(d) {
tt.style("opacity", 0);
});
d3.transition(svg).select(".x.axis").transition().duration(2000)
.call(xAxis);
d3.transition(svg).select(".y.axis").transition().duration(2000)
.call(yAxis);
});
//second button
d3.select("#percapita")
.on("click", function() {
var top = data.sort(function(a, b) {
return d3.descending(+a.emissionpercap, +b.emissionpercap);
});
yScale.domain([0, d3.max(data, function(d) {
return +d.emissionpercap;
})]);
xScale.domain(top.map(function(d) { return d.countrycode; } ));
//update
var barupdate = svg.selectAll("rect");
barupdate.attr("class", "bar")
.transition()
.duration(2000)
.attr("y", h - padding[2])
.attr("x", function(d) {
return xScale(d.countrycode);
})
.attr("width", xScale.rangeBand())
.attr("y", function(d) {
return yScale(d.emissionpercap) + padding[2];
})
.attr("height", function(d) {
return (h - padding[0] - padding[2]) - yScale(d.emissionpercap);
});
d3.selectAll(".bar").on("mousemove", function(d) {
tt.html(" <strong>" + d.countryname + "</strong> has a per capita CO<sub>2</sub> production <br> of <strong>" + d.emissionpercap + "</strong> metric tons")
.style('top', d3.event.pageY - 12 + 'px')
.style('left', d3.event.pageX + 25 + 'px')
.style("opacity", 0.9);
});
d3.selectAll(".bar").on("mouseout", function(d) {
tt.style("opacity", 0);
});
d3.transition(svg).select(".x.axis").transition().duration(2000)
.call(xAxis);
d3.transition(svg).select(".y.axis").transition().duration(2000)
.call(yAxis);
});
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + padding[3] + "," + padding[0] + ")")
.call(yAxis);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (h - padding[2]) +")")
.call(xAxis);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment