「PythonとJavaScriptではじめるデータビジュアライゼーション」を読む

12.2静的ファイルの配信

フォルダ構成
viz/  
    data/  
        nobel_winners.json
    index.html
    script.js

#index.html
<!DOCTYPE html>
<meta charset="utf-8">
<style>
    body{font-family: sans-serif;}
</style>

<h2 id='data-title'></h2>
<div id='data'>
    <pre></pre>
</div>

<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="script.js"></script>

#script.js
d3.json('data/nobel_winners_plus_bornin.json',function(error,data){
    if(error){
        console.log(error);
    }
    d3.select('h2#data-title').text('All the Nobel-winners');
    d3.select('div#data pre').html(JSON.stringify(data,null,4));
});

シエル上でpython -m http.serverで待機状態にする。
Webブラウザーhttp://localhost:8000にアクセスすると

f:id:bitop:20171015095155p:plain

国別に受賞者リストを分ける

ファイルを分割する

フォルダ構成
viz/  
    data/  
        nobel_winners.json
        winners_by_country/
    index.html
    script.js

#group_by_country.py
import pandas as pd

df_winners = pd.read_json('data/nobel_winners_plus_bornin.json')
for name,group in df_winners.groupby('country'):
    group.to_json('data/winners_by_country/' + name + '.json',orient='records')

winners_by_countryフォルダ下に国別のjsonファイルができる。

script.jsを書き換える

#script.js
var loadCountryWinnersJSON = function(country){
    d3.json('data/winners_by_country/' + country + '.json', 
        function(error, data) {
            if (error) {
                console.log(error);
            }
            d3.select('h2#data-title').text('All the Nobel-winners from ' + country);
            d3.select('div#data pre').html(JSON.stringify(data, null, 4));
        });
};

loadCountryWinnersJSON('Australia');

シエル上でpython -m http.serverで待機状態にする。
Webブラウザーhttp://localhost:8000にアクセスすると

f:id:bitop:20171015104020p:plain