LoginSignup
2
1

More than 5 years have passed since last update.

D3.js Heatmap & 画像 & 凡例 (初心者向け-メモレベル)

Last updated at Posted at 2017-09-08

------作成中、完成版ではない-------
もし著作権違反があれば、教えてください!!

■成果物イメージ 

2017-09-08 10_55_45-ヒートマップ.png

test.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ヒートマップ</title>
</head>

<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-legend/2.13.0/d3-legend.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-legend/1.13.0/d3-legend.min.js"></script>

<style>
#div1 {
  z-index:20;
}
svg {
  width:160px;
  height:240px;
}
/* 画像とheatmapを重なるため*/
#canvases {
  position:relative;  
}

/* 画像とheatmapを重なるため*/
.canvas {
  position:absolute;
}


</style>

<body>
<h1>ヒートマップ</h1>


<div id="canvases" style="width:350px;height:280px;">
<img class="canvas" src="/images/o0480048012773923150.jpg" alt="test" style="width:160px;height:240px;">     //画像の描画
<svg class="canvas" id="mygraph"></svg> //heatmapの描画
</div>

//凡例
<svg  id="svg-color-quant" ></svg> 
<script src="/js/d3.js"></script>

</body>
</html>

下記のjsは引用となります

var svgWidth=160;
var svgHeight=240;
var blocksize=20; //ブロックのサイズ
//データセット
var dataset = [
1,2,3,4,5,6,5,3,4,
1,2,2,4,9,1,5,1,5,
2,2,8,0,4,5,5,2,6,
9,2,3,4,5,7,5,3,7,
3,2,6,4,0,6,2,4,8,
1,7,8,2,4,6,3,5,2,
9,2,3,4,5,7,5,3,7,
3,2,6,4,0,6,2,4,8,
3,2,6,4,0,6,2,4,8,
1,2,2,4,9,1,5,1,5,
9,2,3,4,5,7,5,3,7,
]
<!--ヒートマップに表示するカラーの自動計算-->
var color =d3.interpolateHsl("blue","yellow"); //青から黄色にHSLカラー空間で補間する
var maxValue=d3.max(dataset); //最大値を求める
<!-- ヒートマップの準備 -->
var heatmap =d3.select("#mygraph")
.selectAll("rect") //
.data(dataset)
<!--ヒートマップを表示 -->
heatmap.enter()    //
.append("rect")   //四角形・角丸四角形
.attr("class","block") //
.attr("x",function(d,i) { //
return (i % 8) *blocksize; //X座標
})
.attr("y",function(d,i) {
return Math.floor(i/8)*blocksize; //y座標
})
.attr("width",function(d,i) {
return blocksize; //横幅
})
.attr("height",function(d,i) {
return blocksize; //縦幅
})
.style("fill",function(d,i){
return color(d/maxValue); //データからヒートマップに表示する色を求め、表示する
})
.style('opacity',0.3) //透明度 30%
.append("title") //tooltip
.text(function(d){ return d; }) //tooltip

※上記コードの引用先:(超お薦め)
データビジュアライゼーションのためのD3.js徹底入門
https://www.amazon.co.jp/dp/4797368861


var svg = d3.select("#svg-color-quant");
var log = d3.scaleLog()
.domain([ 0.1, 100, 1000 ])
.range(["blue", "yellow"]);
svg.append("g")
.attr("class", "legendLog")
.attr("transform", "translate(20,20)");
var logLegend = d3.legendColor()
.labelFormat(d3.format(".2f"))
.cells([1, 2,3, 4, 5, 6, 7,8,9,10,11,12,13,14,15])
.scale(log);
svg.select(".legendLog")
.call(logLegend);

※上記コードの引用先:(超お薦め)
d3 SVG Legend (v4)
http://d3-legend.susielu.com/

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1