<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Love web applications &#187; 可視化</title>
	<atom:link href="http://blog.hitsuji.me/category/visualization/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.hitsuji.me</link>
	<description>Webアプリつくるの楽しい！つくるネタ、使うネタ、あとは雑談です。</description>
	<lastBuildDate>Sun, 25 Jan 2015 12:49:45 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.1.41</generator>
	<item>
		<title>D3.jsを使って、色相方向に地図を色分けする</title>
		<link>http://blog.hitsuji.me/show-map-with-hue-color-coding-using-d3-js/</link>
		<comments>http://blog.hitsuji.me/show-map-with-hue-color-coding-using-d3-js/#comments</comments>
		<pubDate>Sun, 25 Jan 2015 12:49:45 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=257</guid>
		<description><![CDATA[こんばんは。今日は前回記事の続きです。色相方向に補間して求めた色を使って、実際に地図を色分けしてみました。 題材として、過去の記事「横浜市地図に数値Dataラベルを貼る」で描いた横浜市・区人口ラベル付・・・<a class="readon" href="http://blog.hitsuji.me/show-map-with-hue-color-coding-using-d3-js/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんばんは。今日は<a title="D3.jsで、色相方向（HSV色系）に補完する" href="http://blog.hitsuji.me/hue-color-interpolation-using-d3-js/">前回記事</a>の続きです。色相方向に補間して求めた色を使って、実際に地図を色分けしてみました。</p>
<p>題材として、<a title="横浜市地図に数値Dataラベルを貼る" href="http://blog.hitsuji.me/add-labels-of-population-values-to-yokohama-city-map/">過去の記事「横浜市地図に数値Dataラベルを貼る」</a>で描いた横浜市・区人口ラベル付き地図を用いました。</p>
<p>&nbsp;</p>
<p>ここでの色の範囲は最大値を赤（#ee0000）、最小値を緑（#00ee00）に設定して進めます。</p>
<p>まずは、下記のような普通の方法（？）で色分けしてみます。</p>
<pre class="command">areaGrad = d3.scale.linear().domain([target_min, target_max]).range([hexcode_min, hexcode_max])</pre>
<p>これを使うと、下のような地図が表示されました。※画像をclickすると地図のページに飛びます。</p>
<p><a href="http://static.hitsuji.me/map-yokohama10_2/"><img class="alignnone size-medium_for_2x wp-image-261" src="http://blog.hitsuji.me/app/wp-content/uploads/2015/01/yokohama-map-10_rgb-461x600.png" alt="yokohama-map-10_rgb" width="230" height="300" /></a></p>
<p>かなり残念な配色ですよね。</p>
<p>&nbsp;</p>
<p>一方で、HSV色空間で補間した結果はこんな感じです。※画像をclickすると地図のページに飛びます。</p>
<p><a href="http://static.hitsuji.me/map-yokohama10/"><img class="alignnone size-medium_for_2x wp-image-258" src="http://blog.hitsuji.me/app/wp-content/uploads/2015/01/yokohama-map-10-457x600.png" alt="yokohama-map-10" width="228" height="300" /></a></p>
<p>&nbsp;</p>
<p>ソースコードは、次の通りです。</p>
<script src="https://gist.github.com/1562c11d53bcfc2bc92f.js"></script><noscript><pre><code class="language-coffeescript coffeescript">'use strict'

###
  * 色を変換する関数を定義する
###
hex2rgb = (hexcode) -&gt;
  # rgbに変換する
  result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hexcode);
  if result is null
    console.log &quot;error!&quot;
    return

  [r,g,b] = [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)]
  return [r,g,b]

rgb2hsv = (r,g,b) -&gt;
  # rgb to hsv
  r = r / 255
  g = g / 255
  b = b / 255

  max_v = Math.max(Math.max(r,g), b)
  min_v = Math.min(Math.min(r,g), b)
  v = max_v
  s = max_v - min_v
  if min_v == max_v
    h = 0
  else if min_v == b
    h = 60 * (g-r)/s + 60
  else if min_v == r
    h = 60 * (b-g)/s + 180
  else
    h = 60 * (r-b)/s + 300
  return [h,s,v]

hsv2rgb = (h,s,v) -&gt;
  console.log [h,s,v]
  if h is null
    r = 0
    g = 0
    b = 0
  else
    h_dash = h / 60
    x = s * (1 - Math.abs(h_dash % 2 - 1))
    if h_dash &lt; 1
      [r,g,b] = [s,x,0]
    else if h_dash &lt; 2
      [r,g,b] = [x,s,0]
    else if h_dash &lt; 3
      [r,g,b] = [0,s,x]
    else if h_dash &lt; 4
      [r,g,b] = [0,x,s]
    else if h_dash &lt; 5
      [r,g,b] = [x,0,s]
    else if h_dash &lt; 6
      [r,g,b] = [s,0,x]
    else
      console.log '変換エラー'
      return
  r += (v-s)
  g += (v-s)
  b += (v-s)
  r *= 255
  g *= 255
  b *= 255
  return [Math.round(r),Math.round(g),Math.round(b)]

readTopoFileDone = false
readAttrFileDone = false

# fileから読み込んだdataの格納変数
topo_data = null
attr_data = null
map_width = 500
map_height = 650
svg = null


###
  * JSONファイルを読み込み、地図描画関数mainを呼び出す
###
readTopoFile = (json) -&gt;
  topo_data = json
  readTopoFileDone = true

readAttrFile = (json) -&gt;
  attr_data = json
  readAttrFileDone = true

d3.json(&quot;yokohama_topo_out.json&quot;, (error, json) -&gt;
  if error
    return console.warn error
  readTopoFile(json)
  if readTopoFileDone and readAttrFileDone
    main(topo_data, attr_data))

d3.json(&quot;yokohama_codes_and_stat.json&quot;, (error, json) -&gt;
  if error
    return console.warn(error)
  readAttrFile(json)
  if readTopoFileDone and readAttrFileDone
      main(topo_data, attr_data))


###
  * 地図を描画する
###
main = (topo, attr) -&gt;    
  labelLineHeight = 16
  # 属性情報を入れ直すためのHash Table
  attrHash = []
  
  # attr情報を、IDをkeyとするhash-tableに変換する
  # idをKeyとしたhashテーブル＆property毎のhashテーブルを作成する
  for e in attr
    attrHash[e.cityid]=e
  
  # 人口の最大値と最小値を求めておく
  # --全年齢人口データのみを入れた配列を作成する
  elements = []
  target_key = &quot;ttl&quot;
  for e in attr
    elements.push(e[target_key])
  
  # -- maxとminをとる
  target_max = Math.max.apply(null, elements)
  target_min = Math.min.apply(null, elements)
  
  # svgを追加
  svg = d3.select(&quot;body #map&quot;).append(&quot;svg&quot;).attr(&quot;width&quot;, map_width).attr(&quot;height&quot;, map_height)
  
  # 横浜市のmapを描画する
  yokohama = topojson.object(topo, topo.objects.yokohama)
  
  # 横浜市を中心に指定したメルカトル図法で10万分の1で描画する
  projection = d3.geo.mercator().center([139.59,35.45]).scale(100000).translate([map_width / 2, map_height / 2])
  
  # pathを作成する
  path = d3.geo.path().projection(projection)
  svg.append(&quot;path&quot;).datum(yokohama).attr(&quot;d&quot;, path)
  
  # classを指定する
  svg.selectAll(&quot;.yokohama&quot;).data(yokohama.geometries).enter().append(&quot;path&quot;).attr(&quot;class&quot;, (d) -&gt;
    return &quot;yokohama &quot; + d.properties.name).attr(&quot;d&quot;, path)

  # 色を塗る
  hexcode_max = &quot;#ee0000&quot;
  hexcode_min = &quot;#00ee00&quot;

  # 念のためあらかじめ塗っておく
  svg.selectAll(&quot;path&quot;).attr(&quot;fill&quot;, &quot;#bee59e&quot;)

  # HEXカラーコードからRGBに変換
  [r_min,g_min,b_min] = hex2rgb(hexcode_min)
  [r_max,g_max,b_max] = hex2rgb(hexcode_max)
  # RGB(0-255)からHSVに変換
  [h_min,s_min,v_min] = rgb2hsv(r_min,g_min,b_min)
  [h_max,s_max,v_max] = rgb2hsv(r_max,g_max,b_max)
  areaGrad = d3.scale.linear().domain([target_min, target_max]).range([[h_min,s_min,v_min], [h_max,s_max,v_max]])

  for k, v of attrHash
    [h,s,v] = areaGrad(attrHash[k][target_key])
    [r,g,b] = hsv2rgb(h,s,v)
    svg.selectAll(&quot;.&quot;+k).attr(&quot;fill&quot;, &quot;rgba(#{r},#{g},#{b},1)&quot;)

  # 内部境界に線を引く
  svg.append(&quot;path&quot;)
    .datum(topojson.mesh(topo, topo.objects.yokohama, (a, b) -&gt;
      return a isnt b))
    .attr(&quot;d&quot;, path)
    .attr(&quot;class&quot;, &quot;subunit-boundary&quot;)
  
  # 区コードのラベル貼り
  city_labels = new Array()
  svg.selectAll(&quot;.cityname-label&quot;)
    .data(yokohama.geometries)
      .enter()
        .append(&quot;text&quot;)
        .attr(&quot;class&quot;, (d) -&gt;
          if not (city_labels.indexOf(d.properties.name) &gt; -1)
            city_labels.push(d.properties.name)
          return &quot;cityname-label &quot;+d.properties.name)
        .attr(&quot;transform&quot;, (d) -&gt;
          # 文字をpath中央から、文字高さ1/2分高い位置に貼る
          pos = path.centroid(d)
          pos[1] -= labelLineHeight / 2
          return &quot;translate(&quot; + pos + &quot;)&quot;)
        .attr(&quot;dy&quot;, &quot;.35em&quot;)
        .text((d) -&gt;
          return attrHash[d.properties.name].name)

  # 値ラベル貼り
  svg.selectAll(&quot;.stat-label&quot;)
    .data(yokohama.geometries)
      .enter()
      .append(&quot;text&quot;)
      .attr(&quot;class&quot;, (d) -&gt;
        if not (city_labels.indexOf(d.properties.name) &gt; -1)
          city_labels.push(d.properties.name)
        return &quot;stat-label &quot;+d.properties.name)
      .attr(&quot;transform&quot;, (d) -&gt;
        # 文字をpath中央から、文字高さ1/2分高い位置に貼る
        pos = path.centroid(d)
        pos[1] += labelLineHeight / 2
        return &quot;translate(&quot; + pos + &quot;)&quot;)
      .attr(&quot;dy&quot;, &quot;.35em&quot;)
      .text((d) -&gt;
        return attrHash[d.properties.name][target_key])
  
  # 各最初のエリアのみラベルを表示する
  for id in city_labels
    svg.select(&quot;.cityname-label.&quot;+id).style(&quot;display&quot;, &quot;block&quot;)
    svg.select(&quot;.stat-label.&quot;+id).style(&quot;display&quot;, &quot;block&quot;)
  
  return true
</code></pre></noscript>
<p>&nbsp;</p>
<p>このように、HSV色空間の方が人の直感に合う結果が得られると思いますので、オススメです。</p>
<p>それでは♡</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/show-map-with-hue-color-coding-using-d3-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>D3.jsで、色相方向（HSV色系）に補完する</title>
		<link>http://blog.hitsuji.me/hue-color-interpolation-using-d3-js/</link>
		<comments>http://blog.hitsuji.me/hue-color-interpolation-using-d3-js/#comments</comments>
		<pubDate>Thu, 22 Jan 2015 02:09:01 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=219</guid>
		<description><![CDATA[こんにちは。今日はD3.jsでグラフや地図に色塗りする場合のお話です。 &#160; グラフや地図を値ごとに色分けするには、d3.scale.linear()を使うと簡単です。これは、値に対応した色を・・・<a class="readon" href="http://blog.hitsuji.me/hue-color-interpolation-using-d3-js/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんにちは。今日はD3.jsでグラフや地図に色塗りする場合のお話です。</p>
<p>&nbsp;</p>
<p>グラフや地図を値ごとに色分けするには、d3.scale.linear()を使うと簡単です。これは、値に対応した色を簡単に算出できるので便利です。具体例としては、</p>
<pre class="command">grad = d3.scale.linear().domain([0,1]).range(["#<span style="color: #ff0000;">ff</span><span style="color: #99cc00;">00</span><span style="color: #00ccff;">00</span>", "#<span style="color: #ff0000;">00</span><span style="color: #99cc00;">00</span><span style="color: #00ccff;">ff</span>"])</pre>
<p>とすれば、</p>
<pre class="command">grad(0.5)
&gt; #800080</pre>
<p>という風に、<span style="text-decoration: underline; color: #ff0000;">赤と青の中間</span>の色コードを出力してくれます。</p>
<p>&nbsp;</p>
<p>ところが、ここで言う<span style="text-decoration: underline; color: #ff0000;">赤と青の中間</span>は、RGBの3次元空間での中間を意味しています。視覚的に言えば、次の画像のラインが値域であり、grad(0.5）はライン中央に位置する色ですね。<br />
<img src="http://blog.hitsuji.me/app/wp-content/uploads/2015/01/grad_rgb.svg" alt="RGB Interpolation" width="250" height="250" /></p>
<p>&nbsp;</p>
<p>でも、赤〜青の範囲で色を使うときに、色相で補完したい場合もありますよね。というか、こっちの方が一般的には需要あるのではないでしょうか。</p>
<p>&nbsp;</p>
<p><img src="http://blog.hitsuji.me/app/wp-content/uploads/2015/01/grad_hue.svg" alt="Hue Interpolation" width="200" height="200" /></p>
<p>&nbsp;</p>
<p>円周方向が色相（Hue）です。例えば、Max:赤から Min:青と指定すれば、入力値に応じて赤&gt;橙&gt;黄&gt;緑&gt;青って感じで、色を使えるようにしたい訳です。</p>
<p>&nbsp;</p>
<p>そのためには、</p>
<p>RGB16進数→RGB色系→HSV色系の順に変換して、HSV色系の中でd3.scale.linear()で補完処理を行い、結果をRGB色系に再度変換してattribute指定に使うようにします。HSV色空間とは何ぞや？という方は、<a title="HSV色空間" href="http://ja.wikipedia.org/wiki/HSV%E8%89%B2%E7%A9%BA%E9%96%93" target="_blank">Wikipediaへ。</a></p>
<p>&nbsp;</p>
<p>それぞれの変換を行うスクリプトを書いてみました。</p>
<script src="https://gist.github.com/1288d20c5499ce075770.js"></script><noscript><pre><code class="language-coffeescript coffeescript">hex2rgb = (hexcode) -&gt;
  # rgbに変換する
  result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hexcode);
  if result is null
    console.log &quot;error!&quot;
    return
  
  [r,g,b] = [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)]
  return [r,g,b]</code></pre><pre><code class="language-coffeescript coffeescript">hsv2rgb = (h,s,v) -&gt;
  if h &lt; 0
    r = 0
    g = 0
    b = 0
  else
    h_dash = h / 60
    x = s * (1 - Math.abs(h_dash % 2 - 1))
    if h_dash &lt; 1
      [r,g,b] = [s,x,0]
    else if h_dash &lt; 2
      [r,g,b] = [x,s,0]
    else if h_dash &lt; 3
      [r,g,b] = [0,s,x]
    else if h_dash &lt; 4
      [r,g,b] = [0,x,s]
    else if h_dash &lt; 5
      [r,g,b] = [x,0,s]
    else if h_dash &lt; 6
      [r,g,b] = [s,0,x]
    else
        console.log '変換エラー'
        return
  r += (v-s)
  g += (v-s)
  b += (v-s)
  r *= 255
  g *= 255
  b *= 255
  return [r,g,b]
</code></pre><pre><code class="language-coffeescript coffeescript">rgb2hsv = (r,g,b) -&gt;
  # rgb to hsv
  r = r / 255
  g = g / 255
  b = b / 255
  
  max_v = Math.max(Math.max(r,g), b)
  min_v = Math.min(Math.min(r,g), b)  
  v = max_v
  s = max_v - min_v
  if min_v == max_v
    h = -1
  else if min_v == b
    h = 60 * (g-r)/s + 60
  else if min_v == r
    h = 60 * (b-g)/s + 180
  else
    h = 60 * (r-b)/s + 300
  return [h,s,v]</code></pre></noscript>
<p>&nbsp;</p>
<p>厳密には、黒（R,G,B）=(0,0,0）の場合のHSV色空間におけるHの値は不定/undefinedなのですが（黒は彩度ゼロってことです）、ここのコードではゼロを割り当ててしまっています。それでも、今回の目的の実用上問題なさそうだったからです。</p>
<p>&nbsp;</p>
<p>次回はHSV色系で色補完して、グラフor地図を色分けした具体例を紹介しようと思います。</p>
<p>それではまた♪</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/hue-color-interpolation-using-d3-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>横浜市地図に数値Dataラベルを貼る</title>
		<link>http://blog.hitsuji.me/add-labels-of-population-values-to-yokohama-city-map/</link>
		<comments>http://blog.hitsuji.me/add-labels-of-population-values-to-yokohama-city-map/#comments</comments>
		<pubDate>Thu, 31 Jul 2014 11:56:37 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[TopoJSON]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=174</guid>
		<description><![CDATA[今日は地図の方を進めようと思います。前回記事「横浜市地図を人口に応じて色塗りする」で描いた地図に、区名ラベルだけでなく数値のラベルも添付できるようにしたいと思います。 &#160; &#160; ポリ・・・<a class="readon" href="http://blog.hitsuji.me/add-labels-of-population-values-to-yokohama-city-map/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>今日は地図の方を進めようと思います。<a title="横浜市地図を人口に応じて色塗りする" href="http://blog.hitsuji.me/show-yokohama-city-map-filled-with-colors-according-to-population/">前回記事「横浜市地図を人口に応じて色塗りする」</a>で描いた地図に、区名ラベルだけでなく数値のラベルも添付できるようにしたいと思います。</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h3>ポリゴンの中央にラベルを２行を貼付ける</h3>
<p>区毎のポリゴンの中央にラベルが２行くるように位置を調整しつつ、ラベルを貼っていきます。</p>
<p>実際に描いた地図が次の通り（画像をクリックすると地図ページに飛びます）。</p>
<p><a href="http://static.hitsuji.me/map-yokohama09/"><img class="alignnone size-medium_for_2x wp-image-177" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/07/yokohama_map09-436x600.png" alt="yokohama_map09" width="218" height="300" /></a></p>
<p>&nbsp;</p>
<p>やっていることはカンタン。テキストラベルのtransform属性で指定する高さ方向の位置について、上の行は-0.5行、下の行は+0.5行だけシフトさせているだけです。行間は予め決めてあります（labelLineHight）。</p>
<p>&nbsp;</p>
<p>ちなみに・・・<br />
縦方向の座標は下向きが正なので、通常の感覚と逆方向になります。上方向への移動がマイナス，下がプラスですね。</p>
<p>&nbsp;</p>
<p>ソースコードは次の通り。</p>
<h6>index.html</h6>
<script src="https://gist.github.com/b22bcf139ef5c3bed2e6.js"></script><noscript><pre><code class="language-html html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://d3js.org/topojson.v0.min.js&quot;&gt;&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
h1 {
    font-size: 16px;
}
svg {
    border: 1px solid #aaaaaa;
}
.subunit-boundary {
  fill: none;
  stroke: #777;
  stroke-dasharray: 2,2;
  stroke-linejoin: round;
}
.cityname-label {
    fill-opacity: .5;
    font-size: 8px;
    font-weight: 300;     
    text-anchor: middle;
    display: none;
}
.stat-label {
    fill-opacity: .5;
    font-size: 8px;
    font-weight: 300;
    text-anchor: middle;
    display: none;
}
&lt;/style&gt;
&lt;title&gt;Yokohama city map&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Yokohama city map&lt;/h1&gt;
&lt;div id=&quot;map&quot;&gt;&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    
    // file読み込み制御用
    var readTopofileDone = false;
    var readAttrfileDone = false;
    // filedata格納変数
    var topodata;
    var attrdata;
    
    var map_width = 500;
    var map_height = 650;
    var svg;
    
    function readTopofile(json) {
        topodata = json;
        readTopofileDone = true;
    }
    function readAttrfile(json) {
        attrdata = json;
        readAttrfileDone = true;
    }
    
    d3.json(&quot;yokohama_topo_out.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readTopofile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    d3.json(&quot;yokohama_codes_and_stat.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readAttrfile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    function main(topo, attr) {
        
        var labelLineHight = 16;
        // 属性情報を入れ直すためのHash Table
        var attrHash = new Object();
        
        // attr情報を、IDをkeyとするhash-tableに変換する
        // idをKeyとしたhashテーブル＆property毎のhashテーブルを作成する
        attr.forEach(function(e){
            attrHash[e.cityid]=e;
        });
        
        // 人口の最大値と最小値を求めておく
        // --全年齢人口データのみを入れた配列を作成する
        var elements = [];
        var target_key = &quot;ttl&quot;;
        attr.forEach(function(e){
            elements.push(e[target_key]);
        });
        // -- maxとminをとる
        var target_max = Math.max.apply(null, elements);
        var target_min = Math.min.apply(null, elements);
        
         // svgを追加
        svg = d3.select(&quot;body #map&quot;).append(&quot;svg&quot;)
                .attr(&quot;width&quot;, map_width)
                .attr(&quot;height&quot;, map_height);
        
        // 横浜市のmapを描画する
        var yokohama = topojson.object(topo, topo.objects.yokohama);
        console.log(yokohama);
        
        // 横浜市を中心に指定したメルカトル図法で10万分の1で描画する
        var projection = d3.geo.mercator()
                .center([139.59,35.45])
                .scale(100000)
                .translate([map_width / 2, map_height / 2]);
        
        // pathを作成する
        var path = d3.geo.path().projection(projection);
        svg.append(&quot;path&quot;)
          .datum(yokohama)
          .attr(&quot;d&quot;, path);
        
        // classを指定する
        svg.selectAll(&quot;.yokohama&quot;)
            .data(yokohama.geometries)
        .enter().append(&quot;path&quot;)
            .attr(&quot;class&quot;, function(d) {
                return &quot;yokohama &quot; + d.properties.name;
                })
            .attr(&quot;d&quot;, path);
        
        // 色を塗る
        var areaGrad = d3.scale.linear()
                        .domain([target_min, target_max])
                        .range([&quot;#bee59e&quot;, &quot;#349946&quot;]);
        svg.selectAll(&quot;path&quot;).attr(&quot;fill&quot;, &quot;#bee59e&quot;);
        for (var k in attrHash) {
            svg.selectAll(&quot;.&quot;+k).attr(&quot;fill&quot;, areaGrad(attrHash[k][target_key]));
        }
        
        // 内部境界に線を引く
        svg.append(&quot;path&quot;)
           .datum(topojson.mesh(topo, topo.objects.yokohama, function(a, b) { return a !== b; }))
           .attr(&quot;d&quot;, path)
           .attr(&quot;class&quot;, &quot;subunit-boundary&quot;);
        
        // 区コードのラベル貼り
        var city_labels = new Array();
        svg.selectAll(&quot;.cityname-label&quot;)
            .data(yokohama.geometries)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    if(!(city_labels.indexOf(d.properties.name) &gt; -1)) {
                        city_labels.push(d.properties.name);
                    }
                    return &quot;cityname-label &quot;+d.properties.name; // class名にidを付与
                    })
                .attr(&quot;transform&quot;, function(d) {
                    // 文字をpath中央から、文字高さ1/2分高い位置に貼る
                    var pos = path.centroid(d);
                    pos[1] -= labelLineHight / 2;
                    return &quot;translate(&quot; + pos + &quot;)&quot;;
                })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return attrHash[d.properties.name].name;
                });
        
        // 値ラベル貼り
        svg.selectAll(&quot;.stat-label&quot;)
            .data(yokohama.geometries)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    if(!(city_labels.indexOf(d.properties.name) &gt; -1)) {
                        city_labels.push(d.properties.name);
                    }
                    return &quot;stat-label &quot;+d.properties.name; // class名にidを付与
                    })
                .attr(&quot;transform&quot;, function(d) {
                    // 文字をpath中央から、文字高さ1/2分高い位置に貼る
                    var pos = path.centroid(d);
                    pos[1] += labelLineHight / 2;
                    return &quot;translate(&quot; + pos + &quot;)&quot;;
                })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return attrHash[d.properties.name][target_key];
                });
        
        // 各最初のエリアのみラベルを表示する
        for (var i in city_labels) {
            svg.select(&quot;.cityname-label.&quot;+city_labels[i]).style(&quot;display&quot;, &quot;block&quot;);
            svg.select(&quot;.stat-label.&quot;+city_labels[i]).style(&quot;display&quot;, &quot;block&quot;);
        }
        
    }
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre></noscript>
<p>&nbsp;</p>
<p>動けばよし！という感じのコードになってしまいましたが、数値ラベルも合わせて貼れました♪</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>ただ、濃い緑の背景の箇所は黒いテキストラベルが見づらいですね。背景が濃い場合は文字色を白にすると良いのではないでしょうか。</p>
<p>という訳で、次はこの問題を解決すべく、ラベルの色制御をしてみようと思います。</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/add-labels-of-population-values-to-yokohama-city-map/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>横浜市地図を人口に応じて色塗りする</title>
		<link>http://blog.hitsuji.me/show-yokohama-city-map-filled-with-colors-according-to-population/</link>
		<comments>http://blog.hitsuji.me/show-yokohama-city-map-filled-with-colors-according-to-population/#comments</comments>
		<pubDate>Fri, 25 Jul 2014 02:23:00 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[TopoJSON]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=141</guid>
		<description><![CDATA[こんにちは。昨夜の大雨から一転して真夏の気候で大変ですね。外出時には日傘必須です^^; &#160; 地図を人口の大小に応じて色分けする さて、前回の記事「JSONファイルをCSVファイルに変換する」・・・<a class="readon" href="http://blog.hitsuji.me/show-yokohama-city-map-filled-with-colors-according-to-population/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんにちは。昨夜の大雨から一転して真夏の気候で大変ですね。外出時には日傘必須です^^;</p>
<p>&nbsp;</p>
<h3>地図を人口の大小に応じて色分けする</h3>
<p>さて、前回の記事「<a title="JSONファイルをCSVファイルに変換する" href="http://blog.hitsuji.me/read-json-conv-2-dimension-list-and-write-it-to-csv/">JSONファイルをCSVファイルに変換する</a>」で作成したJSONファイルを使って、横浜市地図を改めて描きます。行政区毎の人口数の大小に応じて、地図を色塗りします。</p>
<p>&nbsp;</p>
<h4>地図を描画する</h4>
<p>早速完成した地図です♪画像をクリックしてくださいね^^</p>
<p><a href="http://static.hitsuji.me/map-yokohama08/"><img class="alignnone size-medium_for_2x wp-image-142" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/07/yokohama_map08-440x600.png" alt="yokohama_map08" width="220" height="300" /></a></p>
<p>&nbsp;</p>
<p>人口が多い区は濃く、少ない区は薄い色に指定してみました。</p>
<p>&nbsp;</p>
<p>元のソースコードはこちら。</p>
<h6>index.html</h6>
<script src="https://gist.github.com/41e2745f0736ae25bc31.js"></script><noscript><pre><code class="language-html html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://d3js.org/topojson.v0.min.js&quot;&gt;&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
h1 {
    font-size: 16px;
}
svg {
    border: 1px solid #aaaaaa;
}
.subunit-boundary {
  fill: none;
  stroke: #777;
  stroke-dasharray: 2,2;
  stroke-linejoin: round;
}
.cityname-label {
    fill-opacity: .5;
    font-size: 8px;
    font-weight: 300;     
    text-anchor: middle;
    display: none;
}
&lt;/style&gt;
&lt;title&gt;Yokohama city map&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Yokohama city map&lt;/h1&gt;
&lt;div id=&quot;map&quot;&gt;&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    
    // file読み込み制御用
    var readTopofileDone = false;
    var readAttrfileDone = false;
    // filedata格納変数
    var topodata;
    var attrdata;
    
    var map_width = 500;
    var map_height = 650;
    var svg;
    
    function readTopofile(json) {
        topodata = json;
        readTopofileDone = true;
    }
    function readAttrfile(json) {
        attrdata = json;
        readAttrfileDone = true;
    }
    
    d3.json(&quot;yokohama_topo_out.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readTopofile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    d3.json(&quot;yokohama_codes_and_stat.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readAttrfile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    function main(topo, attr) {
        
        var labelLineHight = 16;
        // 属性情報を入れ直すためのHash Table
        var attrHash = new Object();
        
        // attr情報を、IDをkeyとするhash-tableに変換する
        // idをKeyとしたhashテーブル＆property毎のhashテーブルを作成する
        attr.forEach(function(e){
            attrHash[e.cityid]=e;
        });
        
        // 人口の最大値と最小値を求めておく
        // --全年齢人口データのみを入れた配列を作成する
        var elements = [];
        var target_key = &quot;ttl&quot;;
        attr.forEach(function(e){
            elements.push(e[target_key]);
        });
        // -- maxとminをとる
        var target_max = Math.max.apply(null, elements);
        var target_min = Math.min.apply(null, elements);
        
         // svgを追加
        svg = d3.select(&quot;body #map&quot;).append(&quot;svg&quot;)
                .attr(&quot;width&quot;, map_width)
                .attr(&quot;height&quot;, map_height);
        
        // 横浜市のmapを描画する
        var yokohama = topojson.object(topo, topo.objects.yokohama);
        console.log(yokohama);
        
        // 横浜市を中心に指定したメルカトル図法で10万分の1で描画する
        var projection = d3.geo.mercator()
                .center([139.59,35.45])
                .scale(100000)
                .translate([map_width / 2, map_height / 2]);
        
        // pathを作成する
        var path = d3.geo.path().projection(projection);
        svg.append(&quot;path&quot;)
          .datum(yokohama)
          .attr(&quot;d&quot;, path);
        
        // classを指定する
        svg.selectAll(&quot;.yokohama&quot;)
            .data(yokohama.geometries)
        .enter().append(&quot;path&quot;)
            .attr(&quot;class&quot;, function(d) {
                return &quot;yokohama &quot; + d.properties.name;
                })
            .attr(&quot;d&quot;, path);
        
        // 色を塗る
        var areaGrad = d3.scale.linear()
                        .domain([target_min, target_max])
                        .range([&quot;#bee59e&quot;, &quot;#349946&quot;]);
        svg.selectAll(&quot;path&quot;).attr(&quot;fill&quot;, &quot;#bee59e&quot;);
        for (var k in attrHash) {
            svg.selectAll(&quot;.&quot;+k).attr(&quot;fill&quot;, areaGrad(attrHash[k][target_key]));
        }
        
        // 内部境界に線を引く
        svg.append(&quot;path&quot;)
           .datum(topojson.mesh(topo, topo.objects.yokohama, function(a, b) { return a !== b; }))
           .attr(&quot;d&quot;, path)
           .attr(&quot;class&quot;, &quot;subunit-boundary&quot;);
        
        // 区コードのラベル貼り
        var city_labels = new Array();
        svg.selectAll(&quot;.cityname-label&quot;)
            .data(yokohama.geometries)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    if(!(city_labels.indexOf(d.properties.name) &gt; -1)) {
                        city_labels.push(d.properties.name);
                    }
                    return &quot;cityname-label &quot;+d.properties.name; /* class名にidを付与 */
                    })
                .attr(&quot;transform&quot;, function(d) {
                    return &quot;translate(&quot; + path.centroid(d) + &quot;)&quot;;
                })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return attrHash[d.properties.name].name;
                });
        
        // 各最初のエリアのみラベルを表示する
        for (var i in city_labels) {
            svg.select(&quot;.cityname-label.&quot;+city_labels[i]).style(&quot;display&quot;, &quot;block&quot;);
        }
        
    }
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre></noscript>
<p>&nbsp;</p>
<p>L.84-93で、区毎の人口数の最大値と最小値を計算しています。</p>
<p><em><span style="color: #808080;">冗長過ぎるコードなので、すっきり直したいですが。</span></em></p>
<p>&nbsp;</p>
<p>L.116-で、各区領域にclass属性を指定しています。</p>
<p>&nbsp;</p>
<p>続いてL.126-で色塗りしています。</p>
<p>D3.jsの機能を使って、色を人口に応じて求める関数を作成します</p>
<pre class="command">areaGrad = d3.scale.linear().domain([target_min, target_max]).range(["#bee59e", "#349946"]);</pre>
<p>d3.scale.linear()は、リニアに補間した結果を返す関数を作成するもので、f = d3.scale.linear()domain([x1, x2]).range([y1, y2])とすると、f(x)は下図のように補間した値yを返してくれます。</p>
<p><img class="alignnone size-large_for_2x wp-image-144" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/07/d3_scale_linear.png" alt="d3_scale_linear" width="600" height="400" /></p>
<p>&nbsp;</p>
<p>さらに、range()には16進数RGB colorも指定できるという優れもので、range([薄い緑, 濃い緑])を指定しました。</p>
<p>domainには、先ほど求めた人口の最小値＆最大値を指定してありますので、</p>
<p><img class="alignnone size-large_for_2x wp-image-145" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/07/d3_scale_linear_ex_2x.png" alt="d3_scale_linear_ex_2x" width="600" height="400" /></p>
<p>&nbsp;</p>
<p>という感じで、L.131でfill指定する色を返してくれます。</p>
<p>&nbsp;</p>
<p>色塗り完成です♪</p>
<p>次回は、人口の数値自体を地図に書き入れる処理を追加したいと思います。</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/show-yokohama-city-map-filled-with-colors-according-to-population/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>横浜市人口棒グラフに目盛りを追加する</title>
		<link>http://blog.hitsuji.me/add-y-axis-to-bar-graph-using-d3-js/</link>
		<comments>http://blog.hitsuji.me/add-y-axis-to-bar-graph-using-d3-js/#comments</comments>
		<pubDate>Mon, 14 Jul 2014 13:02:27 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[棒グラフ]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=123</guid>
		<description><![CDATA[こんばんは。だんだん気候が夏に近づいてきましたね。私は暑いのが苦手なので、エアコンに頼りまくりです^^; &#160; 棒グラフに縦軸を追加する 今日は前回の記事「D3.jsで横浜市の人口棒グラフを表・・・<a class="readon" href="http://blog.hitsuji.me/add-y-axis-to-bar-graph-using-d3-js/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんばんは。だんだん気候が夏に近づいてきましたね。私は暑いのが苦手なので、エアコンに頼りまくりです^^;</p>
<p>&nbsp;</p>
<h3>棒グラフに縦軸を追加する</h3>
<p>今日は前回の記事「D3.jsで横浜市の人口棒グラフを表示する」で描いた棒グラフについて、縦軸を追加することにします。</p>
<p>&nbsp;</p>
<h4>スケール追加はカンタン</h4>
<p>d3.scale()関数を使えばスケールを簡単に作れるみたいです。実装してみた結果が下のグラフです（画像をクリックすると、グラフのページに飛びます♪）。</p>
<p>&nbsp;</p>
<p><a href="http://static.hitsuji.me/stat-yokohama02/"><img class="alignnone wp-image-125 size-large_for_2x" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/07/yokohama_stat02-1200x666.png" alt="yokohama_stat02" width="600" height="333" /></a></p>
<p>&nbsp;</p>
<p>ソースはこちら。軸を描くコードはたった３行です。</p>
<h6>index.html</h6>
<script src="https://gist.github.com/230711fe512df0da62a0.js"></script><noscript><pre><code class="language-html html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://d3js.org/topojson.v0.min.js&quot;&gt;&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
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;
}
.axis path, .axis line {
    fill: none;
    stroke: #000;
    shape-rendering: crispEdges;
}
.axis text {
    font-size: 9px;
}
&lt;/style&gt;
&lt;title&gt;横浜市区別人口&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;横浜市区別人口[千人]&lt;/h1&gt;
&lt;div id=&quot;graph&quot;&gt;&lt;/div&gt;


&lt;script type=&quot;text/javascript&quot;&gt;

    d3.json(&quot;yokohama_stat.json&quot;, function(error, json) {
        if( !error ) {
            main(json);
        }
        return;
    });
    
    function main(stat) {
        
        var svg;
        var graph_width = 800;
        var graph_height = 400;
        var graph_padding = 20;
        var xaxis_margin = 0;
        var yaxis_margin = 25;
        var plotarea_width = graph_width - yaxis_margin - 2 * graph_padding;
        var plotarea_height = graph_height - xaxis_margin - 2 * graph_padding;
        var origin_dx = yaxis_margin + graph_padding;
        var origin_dy = plotarea_height + graph_padding;
        
        var bar_width = 30;
        var bar_space = 10;
        var bar_pitch = bar_width + bar_space;
        var label_padding = 10;
        
        // svgを追加
        svg = d3.select(&quot;#graph&quot;).append(&quot;svg&quot;)
                .attr(&quot;width&quot;, graph_width)
                .attr(&quot;height&quot;, graph_height);
        
        // 横浜市TTLの値を配列から削除する
        stat.splice(0,1);
        
        // 棒グラフを描く
        svg.selectAll(&quot;rect.bar&quot;)
                .data(stat)
                .enter().append(&quot;rect&quot;)
                .attr(&quot;class&quot;,&quot;bar&quot;)
                    .attr(&quot;x&quot;, function(d,i) { return origin_dx + bar_pitch * i + bar_space; })
                    .attr(&quot;y&quot;, function(d,i) { return origin_dy - d.stat['TTL']/1000; })
                    .attr(&quot;width&quot;, bar_width)
                    .attr(&quot;height&quot;, function(d,i) { return d.stat['TTL']/1000; });
                    
        svg.selectAll(&quot;rect.bar&quot;)
                .data(stat)
                .exit()
                .remove();
        
        // ラベルを描く
        svg.selectAll(&quot;.bar-label&quot;)
            .data(stat)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    return &quot;bar-label&quot;;
                    })
                .attr(&quot;transform&quot;, function(d, i) {
                    return &quot;translate(&quot;+ ( origin_dx + bar_pitch*i + bar_space + bar_width/2) +&quot;,&quot;+ (origin_dy - label_padding) +&quot;)rotate(-90)&quot;;
                 })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return d.key;
                });
        svg.selectAll(&quot;rect.bar-label&quot;)
                .data(stat)
                .exit()
                .remove();
        
        // 縦軸を追加する
        var scale = d3.scale.linear().domain([plotarea_height ,0]).range([0, plotarea_height]);
        var axis = d3.svg.axis().scale(scale).orient(&quot;left&quot;).ticks(5);
        svg.append(&quot;g&quot;).attr(&quot;class&quot;,&quot;axis&quot;).attr(&quot;transform&quot;,function(){ return &quot;translate(&quot;+origin_dx+&quot;,&quot;+graph_padding+&quot;)&quot;; }).call(axis);
    
    }
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre></noscript>
<p>&nbsp;</p>
<p>これで縦軸のスケールが描けました。</p>
<p>ざっくりですが、<a title="横浜市区別人口" href="http://kashika.net/stat-yokohama02/" target="_blank">グラフ</a>の値と<a title="横浜市統計ポータルサイト" href="http://www.city.yokohama.lg.jp/ex/stat/jinko/age/new/age-j.html" target="_blank">元の表</a>の値が合ってることが確認できました♥︎</p>
<p>&nbsp;</p>
<p>次はこの人口データを、以前描いた横浜市地図上で表現することを考えてみようと思います。</p>
<p>それではまた♪</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/add-y-axis-to-bar-graph-using-d3-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>D3.jsで横浜市の人口棒グラフを表示する</title>
		<link>http://blog.hitsuji.me/show-bar-graph-of-yokohama-stat-using-d3-js/</link>
		<comments>http://blog.hitsuji.me/show-bar-graph-of-yokohama-stat-using-d3-js/#comments</comments>
		<pubDate>Fri, 11 Jul 2014 02:02:57 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[棒グラフ]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=117</guid>
		<description><![CDATA[こんにちは。今朝は台風が通過する予報だったのでドキドキして起床しましたが、予想外にも快晴でした。 これがいわゆる台風一過でしょうか。とっても良いお天気です♥︎ &#160; 人口を棒グラフで可視化する・・・<a class="readon" href="http://blog.hitsuji.me/show-bar-graph-of-yokohama-stat-using-d3-js/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんにちは。今朝は台風が通過する予報だったのでドキドキして起床しましたが、予想外にも快晴でした。</p>
<p>これがいわゆる台風一過でしょうか。とっても良いお天気です♥︎</p>
<p>&nbsp;</p>
<h3>人口を棒グラフで可視化する</h3>
<p>さて、今日は<a title="Perlで横浜市の区別年齢別人口データを自動入手する" href="http://blog.hitsuji.me/get-stat-of-yokohama-city-population-automatically/">前回の記事「Perlで横浜市の区別年齢別人口データを自動入手する」</a>でWebから入手した横浜市の人口データを棒グラフにしてみたいと思います。</p>
<p>&nbsp;</p>
<h4>D3.jsで棒グラフを描画してみる</h4>
<p>早速グラフを描いてみました。</p>
<p>&nbsp;</p>
<p><a title="tutorials" href="http://ja.d3js.info/alignedleft/tutorials/d3/" target="_blank">D3.jsのチュートリアル</a>などをみると、divを使う方法とsvgを使う方法がありますが、このグラフはsvgを使って描いています。画像をクリックすると、グラフページに飛びます♪</p>
<p>&nbsp;</p>
<p><a href="http://static.hitsuji.me/stat-yokohama01/"><img class="alignnone wp-image-118 size-large_for_2x" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/07/yokohama_stat01-1200x668.png" alt="yokohama_stat01" width="600" height="334" /></a></p>
<p>&nbsp;</p>
<p>コードは次の通りです。</p>
<h6>index.html</h6>
<script src="https://gist.github.com/c48bea307f9755fa254e.js"></script><noscript><pre><code class="language-html html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://d3js.org/topojson.v0.min.js&quot;&gt;&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
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;
}
&lt;/style&gt;
&lt;title&gt;横浜市区別人口&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;横浜市区別人口&lt;/h1&gt;
&lt;div id=&quot;graph&quot;&gt;&lt;/div&gt;


&lt;script type=&quot;text/javascript&quot;&gt;
    var graph_width = 800;
    var graph_height = 400;
    var label_padding = 10;
    var svg;
    
    d3.json(&quot;yokohama_stat.json&quot;, 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(&quot;#graph&quot;).append(&quot;svg&quot;)
                .attr(&quot;width&quot;, graph_width)
                .attr(&quot;height&quot;, graph_height);
        
        // 横浜市TTLの値を配列から削除する
        stat.splice(0,1);
        
        // 棒グラフを描く
        svg.selectAll(&quot;rect.bar&quot;)
                .data(stat)
                .enter().append(&quot;rect&quot;)
                .attr(&quot;class&quot;,&quot;bar&quot;)
                    .attr(&quot;x&quot;, function(d,i) { return bar_pitch * i + bar_space; })
                    .attr(&quot;y&quot;, function(d,i) { return graph_height - d.stat['TTL']/1000; })
                    .attr(&quot;width&quot;, bar_width)
                    .attr(&quot;height&quot;, function(d,i) { return d.stat['TTL']/1000; });
                    
        svg.selectAll(&quot;rect.bar&quot;)
                .data(stat)
                .exit()
                .remove();
        
        // ラベルを描く
        svg.selectAll(&quot;.bar-label&quot;)
            .data(stat)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    return &quot;bar-label&quot;;
                    })
                .attr(&quot;transform&quot;, function(d, i) {
                    return &quot;translate(&quot;+ ( bar_pitch*i + bar_space + bar_width/2) +&quot;,&quot;+ (graph_height - label_padding) +&quot;)rotate(-90)&quot;;
                 })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return d.key;
                });
        svg.selectAll(&quot;rect.bar-label&quot;)
                .data(stat)
                .exit()
                .remove();
    }
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre></noscript>
<p>&nbsp;</p>
<p>L56は、読み込んだJSONファイルの0番目の要素に横浜市全体の人口データが入っており、グラフから削除するためにカットしています。</p>
<pre class="command">stat.splice(0,1);</pre>
<p>&nbsp;</p>
<p>L59から棒グラフを描画、</p>
<p>L72から区名を描画する処理を記述しています。</p>
<p>&nbsp;</p>
<p>L82でラベルを-90度回転させる処理は、回転基準アンカーを文字の位置にしたいので、transrate()rotate()で指定しております。（x,yで文字の位置を指定する書き方だと、回転基準が原点0,0になってしまう=&gt;<a title="rotate-x-axis-text-in-d3" href="http://stackoverflow.com/questions/11252753/rotate-x-axis-text-in-d3" target="_blank">stackoverflow</a>）</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>棒グラフが描けました♥︎</p>
<p>データを自動収集するスクリプトと連動させれば、人口グラフを自動更新するサイトが作れそうですね。</p>
<p>&nbsp;</p>
<p>でも・・・このままだと縦軸に単位が入っていないので値が不明です（^^;</p>
<p>次回は、縦方向の目盛りを追加していきます。</p>
<p>&nbsp;</p>
<p>それでは、よい一日をお過ごしください！</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/show-bar-graph-of-yokohama-stat-using-d3-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>横浜市地図に区名を表示する</title>
		<link>http://blog.hitsuji.me/show-yokohama-city-map-divided-into-administrative-divisions-with-its-each/</link>
		<comments>http://blog.hitsuji.me/show-yokohama-city-map-divided-into-administrative-divisions-with-its-each/#comments</comments>
		<pubDate>Sat, 28 Jun 2014 05:41:17 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[TopoJSON]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=103</guid>
		<description><![CDATA[こんにちは。梅雨で毎日ジメジメしていますが、気分だけは元気にブログを更新しようと思います。 &#160; 横浜市地図に日本語区名を表示する さて、今日でようやく横浜市地図に区名ラベルを表示できます。以・・・<a class="readon" href="http://blog.hitsuji.me/show-yokohama-city-map-divided-into-administrative-divisions-with-its-each/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんにちは。梅雨で毎日ジメジメしていますが、気分だけは元気にブログを更新しようと思います。</p>
<p>&nbsp;</p>
<h3>横浜市地図に日本語区名を表示する</h3>
<p>さて、今日でようやく横浜市地図に区名ラベルを表示できます。以前書いた記事「<a title="横浜市地図の各区に１つだけラベル表示する" href="http://blog.hitsuji.me/show-yokohama-city-map-with-label-of-unique-id/">横浜市地図の各区に１つだけラベル表示する</a>」で紹介したコードを、前回の記事「<a title="2つのJSONファイルを読み込む" href="http://blog.hitsuji.me/read-2-jsons-using-d3-js/">2つのJSONファイルを読み込む</a>」のコードでModifyしました。</p>
<p>&nbsp;</p>
<h4>横浜市地図の完成です♪</h4>
<p>下のような地図が出来上がりました。画像をクリックすると、地図ページに飛びます。</p>
<p><a href="http://static.hitsuji.me/map-yokohama07/"><img class="alignnone wp-image-104 size-medium_for_2x" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/06/yokohama_map07-442x600.png" alt="yokohama_map07" width="221" height="300" /></a></p>
<p>&nbsp;</p>
<p>コードは次の通りです。</p>
<h6>index.html</h6>
<script src="https://gist.github.com/f5024f3d9db4536887a9.js"></script><noscript><pre><code class="language-html html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://d3js.org/topojson.v0.min.js&quot;&gt;&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
h1 {
    font-size: 16px;
}
svg {
    border: 1px solid #aaaaaa;
}
.subunit-boundary {
  fill: none;
  stroke: #777;
  stroke-dasharray: 2,2;
  stroke-linejoin: round;
}
.cityname-label {
    fill-opacity: .5;
    font-size: 8px;
    font-weight: 300;     
    text-anchor: middle;
    display: none;
}
&lt;/style&gt;
&lt;title&gt;Yokohama city map&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Yokohama city map&lt;/h1&gt;
&lt;div id=&quot;map&quot;&gt;&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    
    // file読み込み制御用
    var readTopofileDone = false;
    var readAttrfileDone = false;
    // filedata格納変数
    var topodata;
    var attrdata;
    
    var map_width = 500;
    var map_height = 650;
    var svg;
    
    function readTopofile(json) {
        topodata = json;
        readTopofileDone = true;
    }
    function readAttrfile(json) {
        attrdata = json;
        readAttrfileDone = true;
    }
    
    d3.json(&quot;yokohama_topo_out.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readTopofile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    d3.json(&quot;yokohama_codes.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readAttrfile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    function main(topo, attr) {
        
        var labelLineHight = 16;
        // 属性情報を入れ直すためのHash Table
        var attrHash = new Object();
        
        // attr情報を、IDをkeyとするhash-tableに変換する
        // idをKeyとしたhashテーブル＆property毎のhashテーブルを作成する
        attr.forEach(function(e){
            attrHash[e.cityid]=e;
        });
        
         // svgを追加
        svg = d3.select(&quot;body #map&quot;).append(&quot;svg&quot;)
                .attr(&quot;width&quot;, map_width)
                .attr(&quot;height&quot;, map_height);
                
        // 横浜市のmapを描画する
        var yokohama = topojson.object(topo, topo.objects.yokohama);
        console.log(yokohama);
        
        // 横浜市を中心に指定したメルカトル図法で10万分の1で描画する
        var projection = d3.geo.mercator()
                .center([139.59,35.45])
                .scale(100000)
                .translate([map_width / 2, map_height / 2]);
        
        // pathを作成する
        var path = d3.geo.path().projection(projection);
        svg.append(&quot;path&quot;)
          .datum(yokohama)
          .attr(&quot;d&quot;, path);
        
        // 色を塗る
        svg.selectAll(&quot;path&quot;).attr(&quot;fill&quot;, &quot;#bee59e&quot;);
        
        // 内部境界に線を引く
        svg.append(&quot;path&quot;)
           .datum(topojson.mesh(topo, topo.objects.yokohama, function(a, b) { return a !== b; }))
           .attr(&quot;d&quot;, path)
           .attr(&quot;class&quot;, &quot;subunit-boundary&quot;);
        
        // 区コードのラベル貼り
        var city_labels = new Array();
        svg.selectAll(&quot;.cityname-label&quot;)
            .data(yokohama.geometries)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    if(!(city_labels.indexOf(d.properties.name) &gt; -1)) {
                        city_labels.push(d.properties.name);
                    }
                    return &quot;cityname-label &quot;+d.properties.name; /* class名にidを付与 */
                    })
                .attr(&quot;transform&quot;, function(d) {
                    return &quot;translate(&quot; + path.centroid(d) + &quot;)&quot;;
                })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return attrHash[d.properties.name].name;
                });
        
        // 各最初のエリアのみラベルを表示する
        for (var i in city_labels) {
            svg.select(&quot;.cityname-label.&quot;+city_labels[i]).style(&quot;display&quot;, &quot;block&quot;);
        }
        
    }
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre></noscript>
<p>&nbsp;</p>
<p>変更点は２カ所だけです。</p>
<h5>属性データの構造を、&#8221;id&#8221;+団体コードをキーとするHashに変換する</h5>
<p>JSONファイルから読み込んだデータ配列は、そのままだと使いづらいので、団体コードをキーとするHashテーブル（attr =&gt; attrHash）に組み直します。</p>
<p>&nbsp;</p>
<h5>ラベルを区名に変更する</h5>
<p>区名を貼るコードについて、d.properties.nameの箇所を、attrHash[d.properties.name].nameに書き換えます。</p>
<p>&nbsp;</p>
<p>やっと普通の横浜市地図が描けました（笑）。</p>
<p>次は、横浜市の人口データの表示に進もうと思います。</p>
<p>それではまた♥︎</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/show-yokohama-city-map-divided-into-administrative-divisions-with-its-each/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>2つのJSONファイルを読み込む</title>
		<link>http://blog.hitsuji.me/read-2-jsons-using-d3-js/</link>
		<comments>http://blog.hitsuji.me/read-2-jsons-using-d3-js/#comments</comments>
		<pubDate>Thu, 19 Jun 2014 11:51:53 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[TopoJSON]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=98</guid>
		<description><![CDATA[こんばんは。今夜も前回の記事「区名と行政団体コードを書き並べたCSVからJSONファイルを作成する」の続きで、せっせと地図を描き進めようと思います。 &#160; D3.jsのJSON読み込みは非同期・・・<a class="readon" href="http://blog.hitsuji.me/read-2-jsons-using-d3-js/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんばんは。今夜も<a title="区名と行政団体コードを書き並べたCSVからJSONファイルを作成する" href="http://blog.hitsuji.me/convert-csv-listing-words-name-and-their-codes-to-json/">前回の記事「区名と行政団体コードを書き並べたCSVからJSONファイルを作成する」</a>の続きで、せっせと地図を描き進めようと思います。</p>
<p>&nbsp;</p>
<h4>D3.jsのJSON読み込みは非同期処理</h4>
<p>D3.jsでJSONファイルを読み込むには、</p>
<pre class="command">d3.js(filename)</pre>
<p>という関数が用意されており、とても簡単に利用することができます。</p>
<p>&nbsp;</p>
<p>しかし、２つのファイルを読み込むときは若干面倒です。２ファイル読み込みがそれぞれ独立している処理なので、両方のファイルが読み込まれるのを待ってから、main処理を開始しなければなりません。</p>
<p>&nbsp;</p>
<h4>制御用フラグを使う</h4>
<p>２ファイル両方の読み込みが終わるのを待つ必要があります。そのため、制御用に各ファイルの読み込み完了フラグを用意しておき、ファイル読み込み完了した後でフラグを立てるようにします。そして、両方のフラグが立った時に初めてmain()を呼び出します。</p>
<p>&nbsp;</p>
<p>こんな感じです。</p>
<h6>index.html (scriptの一部)</h6>
<script src="https://gist.github.com/fc88e660c80c6eae78be.js"></script><noscript><pre><code class="language-javascript javascript">// file読み込み制御用
var readTopofileDone = false;
var readAttrfileDone = false;
// filedata格納変数
var topodata;
var attrdata;

var map_width = 500;
var map_height = 650;
var svg;

function readTopofile(json) {
    topodata = json;
    readTopofileDone = true;
}
function readAttrfile(json) {
    attrdata = json;
    readAttrfileDone = true;
}

d3.json(&quot;yokohama_topo_out.json&quot;, function(error, json) {
    if(error) return console.warn(error);
        readTopofile(json);
        if (readTopofileDone &amp;&amp; readAttrfileDone) {
            main(topodata, attrdata);
        }
    });

d3.json(&quot;yokohama_codes.json&quot;, function(error, json) {
    if(error) return console.warn(error);
        readAttrfile(json);
        if (readTopofileDone &amp;&amp; readAttrfileDone) {
            main(topodata, attrdata);
        }
    });

function main(topo, attr) {
    // break
}</code></pre></noscript>
<p>&nbsp;</p>
<p>main関数内でbreakしてみました。</p>
<p><img class="alignnone size-large_for_2x wp-image-99" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/06/break-1200x720.png" alt="break" width="600" height="360" /></p>
<p>&nbsp;</p>
<p>ちょっと見づらいですが、attrとtopoの両方の変数がちゃんと見えるのを確認しました♥︎</p>
<p>&nbsp;</p>
<p>今日はここまで。</p>
<p>次回は属性情報（区名）を使って、地図上のラベルをコードから名前に変えます！</p>
<p>それでは〜</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/read-2-jsons-using-d3-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>区名と行政団体コードを書き並べたCSVからJSONファイルを作成する</title>
		<link>http://blog.hitsuji.me/convert-csv-listing-words-name-and-their-codes-to-json/</link>
		<comments>http://blog.hitsuji.me/convert-csv-listing-words-name-and-their-codes-to-json/#comments</comments>
		<pubDate>Sat, 14 Jun 2014 12:33:56 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[CSV]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[UTF-8]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=94</guid>
		<description><![CDATA[こんばんは。今日は、横浜市の区名と&#8221;id&#8221;+行政団体コードをリストアップしたCSVファイルから、JSONファイルにコンバートします。これを後に、TopoJSONファイルと一緒に・・・<a class="readon" href="http://blog.hitsuji.me/convert-csv-listing-words-name-and-their-codes-to-json/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんばんは。今日は、横浜市の区名と&#8221;id&#8221;+行政団体コードをリストアップしたCSVファイルから、JSONファイルにコンバートします。これを後に、TopoJSONファイルと一緒に読み込んで、横浜市地図のラベル表示に使う訳です。（地図表示については、<a title="横浜市地図の各区に１つだけラベル表示する" href="http://blog.hitsuji.me/show-yokohama-city-map-with-label-of-unique-id/">前回までの記事</a>を読んでね）</p>
<p>&nbsp;</p>
<h4>CSVファイルを用意する</h4>
<p>区名と団体コードをリストアップしたCSVファイルをUTF-8エンコードで作成します。ちなみに、もしあなたがMac使いなら、NumbersでUTF-8でさくっと出力することができます。Excelだとshift-jisが基本なので、適当なエディタでUTF-8に変換してくださいねー</p>
<h6>yokohama_codes.csv</h6>
<script src="https://gist.github.com/41f4f657f8fb67184a44.js"></script><noscript><pre><code class="language-csv csv">cityid,name
id141011,鶴見区
id141020,神奈川区
id141038,西区
id141046,中区
id141054,南区
id141062,保土ヶ谷区
id141071,磯子区
id141089,金沢区
id141097,港北区
id141101,戸塚区
id141119,港南区
id141127,旭区
id141135,緑区
id141143,瀬谷区
id141151,栄区
id141160,泉区
id141178,青葉区
id141186,都筑区</code></pre></noscript>
<p>&nbsp;</p>
<h4>PythonでCSVからJSONに変換する</h4>
<p>１行目はカラム名と見なして要素名とし、行毎にDictionaryを作成、Listにポンポン入れて最後にJSON形式で書き出します。</p>
<h6>conv_csv_to_json.py</h6>
<script src="https://gist.github.com/82743ce5eecbf1b02c69.js"></script><noscript><pre><code class="language-python python">#coding:utf-8
'''
Created on 2014/03/27

@author: Tae Matsumoto
CSVファイルを読み込み、同名のJSONファイルを出力します。
'''

import csv, json

filename = 'yokohama_codes'

header = []
data = []

def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
    # csv.py doesn't do Unicode; encode temporarily as UTF-8:
    csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),dialect=dialect, **kwargs)
    for row in csv_reader:
        # decode UTF-8 back to Unicode, cell by cell:
        yield [unicode(cell, 'utf-8') for cell in row]

def utf_8_encoder(unicode_csv_data):
    for line in unicode_csv_data:
        yield line.encode('utf-8')

with open(filename + '.csv', 'rU') as csvfile:
    spamreader = unicode_csv_reader(csvfile, dialect=csv.excel)
    is_first = True
    
    for row in spamreader:
        if is_first:
            header = row[:]
            is_first = False
            continue
        items = {}
        for i in range(0, len(row)):
            item = row[i]
            items[header[i]] = item
        data.append(items)

with open(filename+'.json', 'w') as f:
    json.dump(data, f, ensure_ascii=False, indent=2, encoding='utf8')
    f.close()
</code></pre></noscript>
<p>&nbsp;</p>
<p>JSONファイルに日本語が含まれるので、json.dumpにensure_ascii=falseとencoding=&#8217;utf8&#8217;を指定します。</p>
<p><a title="saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence" href="http://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence" target="_blank">http://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence</a></p>
<p>&nbsp;</p>
<p>上手くできました♥︎</p>
<p>次回は、今日作成したJSONファイルと前回作成した地図をMixして、横浜市地図に区名ラベルを表示できるようにしたいと思います。</p>
<p>それでは、また♪</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/convert-csv-listing-words-name-and-their-codes-to-json/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>横浜市地図の各区に１つだけラベル表示する</title>
		<link>http://blog.hitsuji.me/show-yokohama-city-map-with-label-of-unique-id/</link>
		<comments>http://blog.hitsuji.me/show-yokohama-city-map-with-label-of-unique-id/#comments</comments>
		<pubDate>Thu, 12 Jun 2014 01:52:34 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[TopoJSON]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=86</guid>
		<description><![CDATA[こんにちは。今日は、前回記事「区名を英数字コードに置換する」でTopoJSONファイルの中の区名をID番号に書き換えたものを使って、再度横浜市地図を表示してみます。 &#160; 区名の代わりに行政団・・・<a class="readon" href="http://blog.hitsuji.me/show-yokohama-city-map-with-label-of-unique-id/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんにちは。今日は、<a title="区名を英数字コードに置換する" href="http://blog.hitsuji.me/replacement-from-word-name-to-its-code/">前回記事「区名を英数字コードに置換する」</a>でTopoJSONファイルの中の区名をID番号に書き換えたものを使って、再度横浜市地図を表示してみます。</p>
<p>&nbsp;</p>
<h4>区名の代わりに行政団体コードをラベル表示する</h4>
<p><a title="地図に区名を表示する" href="http://blog.hitsuji.me/show-words-name-on-yokohama-city-map/">前々回の記事「地図に区名を表示する」</a>で利用したindex.htmlをそのまま流用して、地図表示してみます。（読み込むTopoJSONファイルを、区名=&gt;コードに置換したものに変えるだけです）</p>
<p><a href="http://static.hitsuji.me/map-yokohama04/"><img class="alignnone size-medium_for_2x wp-image-87" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/06/yokohama_map04-439x600.png" alt="yokohama_map04" width="219" height="300" /></a></p>
<p>TopoJSONファイルの区名を&#8221;id&#8221;+団体コードに書き換えたので、地図上のラベルもコードに置き換わりました。</p>
<p>&nbsp;</p>
<h4>各区１つだけラベルを表示する</h4>
<p>このままだと、前々回の記事と同様に同じ番号が重複表示されているので、修正します。</p>
<h6>index.html</h6>
<script src="https://gist.github.com/dd8d6440d6b06b6fa330.js"></script><noscript><pre><code class="language-html html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://d3js.org/topojson.v0.min.js&quot;&gt;&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
h1 {
    font-size: 16px;
}
svg {
    border: 1px solid #aaaaaa;
}
.subunit-boundary {
  fill: none;
  stroke: #777;
  stroke-dasharray: 2,2;
  stroke-linejoin: round;
}
.cityname-label {
    fill-opacity: .5;
    font-size: 8px;
    font-weight: 300;     
    text-anchor: middle;
    display: none;
}
&lt;/style&gt;
&lt;title&gt;Yokohama city map&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Yokohama city map&lt;/h1&gt;
&lt;div id=&quot;map&quot;&gt;&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    var map_width = 500;
    var map_height = 650;
    var svg;
    
    d3.json(&quot;yokohama_topo_out.json&quot;, function(error, json) {
        if( !error ) {
            main(json);
        }
        return;
    });
    
    function main(topo) {
        
        var labelLineHight = 16;
         // svgを追加
        svg = d3.select(&quot;body&quot;).append(&quot;svg&quot;)
                .attr(&quot;width&quot;, map_width)
                .attr(&quot;height&quot;, map_height);
                
        // 横浜市のmapを描画する
        var yokohama = topojson.object(topo, topo.objects.yokohama);
        console.log(yokohama);
        
        // 横浜市を中心に指定したメルカトル図法で10万分の1で描画する
        var projection = d3.geo.mercator()
                .center([139.59,35.45])
                .scale(100000)
                .translate([map_width / 2, map_height / 2]);
        
        // pathを作成する
        var path = d3.geo.path().projection(projection);
        svg.append(&quot;path&quot;)
          .datum(yokohama)
          .attr(&quot;d&quot;, path);
        
        // 色を塗る
        svg.selectAll(&quot;path&quot;).attr(&quot;fill&quot;, &quot;#bee59e&quot;);
        
        // 内部境界に線を引く
        svg.append(&quot;path&quot;)
           .datum(topojson.mesh(topo, topo.objects.yokohama, function(a, b) { return a !== b; }))
           .attr(&quot;d&quot;, path)
           .attr(&quot;class&quot;, &quot;subunit-boundary&quot;);
        
        // 区コードのラベル貼り
        var city_labels = new Array();
        svg.selectAll(&quot;.cityname-label&quot;)
            .data(yokohama.geometries)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    if(!(city_labels.indexOf(d.properties.name) &gt; -1)) {
                        city_labels.push(d.properties.name);
                    }
                    return &quot;cityname-label &quot;+d.properties.name; /* class名にidを付与 */
                    })
                .attr(&quot;transform&quot;, function(d) {
                    return &quot;translate(&quot; + path.centroid(d) + &quot;)&quot;;
                })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return d.properties.name;
                });
        
        // 各最初のエリアのみラベルを表示する
        for (var i in city_labels) {
            svg.select(&quot;.cityname-label.&quot;+city_labels[i]).style(&quot;display&quot;, &quot;block&quot;);
        }
        
    }
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre></noscript>
<p>まず区毎にラベリングしたいので、&#8221;id&#8221;+団体コードの文字列をclass属性に追加しました(L80,86-88)。そして冒頭のスタイル指定でラベルを一旦全て非表示にしておきます(L.25)。</p>
<p>地図描画処理に続いてラベル追加処理を終えた後（この時点では全てのラベルはdisplay:noneのまま）、for文で各団体コードについて１つのラベルのみdisplay:blockに書き換える処理を入れました(L.100-102)。</p>
<p><a href="http://static.hitsuji.me/map-yokohama05/"><img class="alignnone size-medium_for_2x wp-image-88" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/06/yokohama_map05-440x600.png" alt="yokohama_map05" width="220" height="300" /></a></p>
<p>重複してラベル表示されていた箇所が消えました♥︎</p>
<p>でも、このままだとラベル名が団体コードってイマイチですよね。次は、これらの団体コードを再度区名に置き換えたいと思います。それではまた！</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/show-yokohama-city-map-with-label-of-unique-id/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
