Skip to content

Instantly share code, notes, and snippets.

@hitsujixgit
Created July 11, 2014 01:26
Show Gist options
  • Save hitsujixgit/c48bea307f9755fa254e to your computer and use it in GitHub Desktop.
Save hitsujixgit/c48bea307f9755fa254e to your computer and use it in GitHub Desktop.
Including a JSON file, it show bar graph.
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v0.min.js"></script>
<style type="text/css">
body {
font-family: 'Lucida Grande','Hiragino Kaku Gothic ProN', Meiryo, sans-serif;
}
h1 {
font-size: 16px;
}
svg {
border: solid 1px #aaa;
}
.bar {
fill: #004E9E;
}
.bar-label {
fill: #ffffff;
}
</style>
<title>横浜市区別人口</title>
</head>
<body>
<h1>横浜市区別人口</h1>
<div id="graph"></div>
<script type="text/javascript">
var graph_width = 800;
var graph_height = 400;
var label_padding = 10;
var svg;
d3.json("yokohama_stat.json", function(error, json) {
if( !error ) {
main(json);
}
return;
});
function main(stat) {
var bar_width = 30;
var bar_space = 10;
var bar_pitch = bar_width + bar_space;
// svgを追加
svg = d3.select("#graph").append("svg")
.attr("width", graph_width)
.attr("height", graph_height);
// 横浜市TTLの値を配列から削除する
stat.splice(0,1);
// 棒グラフを描く
svg.selectAll("rect.bar")
.data(stat)
.enter().append("rect")
.attr("class","bar")
.attr("x", function(d,i) { return bar_pitch * i + bar_space; })
.attr("y", function(d,i) { return graph_height - d.stat['TTL']/1000; })
.attr("width", bar_width)
.attr("height", function(d,i) { return d.stat['TTL']/1000; });
svg.selectAll("rect.bar")
.data(stat)
.exit()
.remove();
// ラベルを描く
svg.selectAll(".bar-label")
.data(stat)
.enter()
.append("text")
.attr("class", function(d) {
return "bar-label";
})
.attr("transform", function(d, i) {
return "translate("+ ( bar_pitch*i + bar_space + bar_width/2) +","+ (graph_height - label_padding) +")rotate(-90)";
})
.attr("dy", ".35em")
.text(function(d) {
return d.key;
});
svg.selectAll("rect.bar-label")
.data(stat)
.exit()
.remove();
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment