<!doctype html>
<head>
<title>svgGraph</title>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="../jQuery/jquery.csv-0.71.min.js"></script>
<script>
var namespaceURI = "http://www.w3.org/2000/svg";
var settings = {
"2012":{color:"#ffff00", slide:0},
"2013":{color:"#ff7f00", slide:10},
"2014":{color:"#ff0000", slide:20}
};
window.onload = generate;
function generate()
{
var svg = document.getElementById("svg");
var data = document.getElementById("data");
var tbl = $.csv.toObjects(data.value);
while (svg.firstChild) {
svg.removeChild(svg.firstChild);
}
// 凡例
var index = 0;
for (var key in settings) {
var y = ++index * 30;
var r = document.createElementNS(namespaceURI, "rect");
r.setAttribute("x", 50);
r.setAttribute("y", y);
r.setAttribute("width", 20);
r.setAttribute("height", 20);
r.setAttribute("stroke", "#000000");
r.setAttribute("fill", settings[key].color);
svg.appendChild(r);
var t = document.createElementNS(namespaceURI, "text");
t.setAttribute("x", 80);
t.setAttribute("y", y + 20);
svg.appendChild(t);
t.textContent = key;
};
// 月
for (var i = 1; i <= 12; i++) {
var t = document.createElementNS(namespaceURI, "text");
t.setAttribute("x", i * 50);
t.setAttribute("y", 420);
svg.appendChild(t);
t.textContent = i + "月";
}
// 棒グラフ
$(tbl).each(function(){
var year = settings[this.Year];
var height = this.Yen / 20;
var r = document.createElementNS(namespaceURI, "rect");
r.setAttribute("x", this.Month * 50 + year.slide);
r.setAttribute("y", 400 - height);
r.setAttribute("width", 20);
r.setAttribute("height", height);
r.setAttribute("stroke", "#000000");
r.setAttribute("fill", year.color);
svg.appendChild(r);
});
}
</script>
</head>
<body>
<svg id="svg" width=800 height=480></svg>
<textarea id="data" cols=40 rows=20>
Year,Month,kWh,Yen
2012,1,130,3172
2012,2,142,3447
2012,3,160,3877
2012,4,138,3380
2012,5,120,2958
2012,6,116,2909
2012,7,112,2870
2012,8,146,3708
2012,9,203,5106
2012,10,149,3862
2012,11,138,3557
2012,12,121,3104
2013,1,134,3398
2013,2,109,2808
2013,3,87,2400
2013,4,93,2554
2013,5,106,2885
2013,6,82,2452
2013,7,92,2695
2013,8,176,4845
2013,9,226,6240
2013,10,133,3675
2013,11,106,2999
2013,12,94,2728
2014,1,133,3603
2014,2,118,3221
2014,3,111,3110
2014,4,112,3188
2014,5,102,3127
2014,6,97,3020
2014,7,128,3776
2014,8,193,5666
</textarea><br>
<br>
<button onclick="generate()">generate</button>
</body>