Tag: javascript Tag: d3js Tag: グラフ

d3.js

グラフ作成のライブラリ。
IE9以降、Chrome、Firefox等で利用出来る。





リンク

D3.js - Data-Driven Documents

https://d3js.org/

JP Home

https://github.com/d3/d3/wiki/JP-Home

日本語ドキュメント

D3.js例文辞典




書籍

データビジュアライゼーションのためのD3.js徹底入門 Webで魅せるグラフ&チャートの作り方

  • 古籏 一浩 (著)

サンプルが多く、分かりやすい。




適当なテスト

 意味は特に無い練習。

HTMLタグの要素を時間を掛けて変形

<html>
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
 
<body>
<div id="hoge" style="position:absolute;width:400px;height:400px;background-color:yellow;"></div>
 
<script>
//d3.select("body").style("background-color", "black");
 
d3.selectAll("p").style("color", function() {
  return "hsl(" + Math.random() * 360 + ",100%,50%)";
});
 
 
d3.select("body")
  .selectAll("p")
  .data([4, 8, 15, 16, 23, 42])
  .enter().append("p")
    .text(function(d) { return "I’m number " + d + "!"; });
    
 
d3.select("body").transition()
.duration(20000)
    .style("background-color", "black")
    .style("color", "white")
    .style("font-size", "300%");
    
 
// div または #hoge または div#hoge
d3.select("div#hoge").transition()
.duration(10000)
.style("left", "300px")
.style("width", "50px")
.style("height", "50px")
.style("background-color", "black");
   
</script>
</body>
</html>

画像の説明




タグPをいじる

http://ja.d3js.node.ws/ を参考に練習。
firefoxとchromeでappendの動きが違った。なぜ?

<html>
<body>
 
<input type="button" id="btn" value="実行1" onclick="d3_test1();">
<input type="button" id="btn" value="実行2" onclick="d3_test2();">
<input type="button" id="btn" value="実行3" onclick="d3_test3();">
 
<hr>
 
<p>1111111</p>
<p>22222222</p>
<p>3333333</p>
<p>4444444</p>
 
 
 
 
 
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
 
 
<script>
 
function d3_test1() {
	var selP =d3.selectAll("p");
	selP.style("color",function() {
		return "hsl(" + Math.random() * 360 + ",100%,50%)";
	});
}
 
 
 
function d3_test2() {
	var selP =d3.selectAll("p");
	selP.data([10,15,20,25,30,35])
		.enter().append("p")
		.text(function(d) { return "append:"+d;})
		;
 
	selP =d3.selectAll("p");
	selP.style("color",function() {
			return "hsl(" + Math.random() * 360 + ",100%,50%)";
		})
		.style("font-size",function(d) {
			return d+"px";
		})
		;
}
 
 
function d3_test3() {
	var selP =d3.selectAll("p");
	selP.data([10,15])
		.exit().remove()
		;
}
 
 
 
</script>
 
 
</body>
</html>


文字

文字を追加する

<svg id="hogehoge"></svg>
 
<!-- というのがHTMLであって、次の様なJavaScriptのコード -->
 
<script>
var svg = d3.select("#hogehoge").attr("width", 640).attr("height",480);
 
svg.append("text")
	.text("普通のサーバーなら漢字も表示可能")
	.attr("font-size","12px")
	.attr("x",35)
	.attr("y",15)
	.style("font-weight", "500")
	.attr("stroke", 'none')
	.attr("fill", 'red')
	;
</script>

文字は「.attr("stroke", 'none')」としておかないと、やや太い字になる。