17
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

geopandasによる地理データのアニメーション

Last updated at Posted at 2017-06-09

はじめに

geopandasはpandasの拡張で、地理データを含むデータをpandasのように表形式で扱うことができるpythonのライブラリーです。geopandasには地理データ可視化のための機能も含まれています。といってもデータをそのままmatplotlibに渡しているだけなので、基本的にはふつうにmatplotlibでアニメーションを作成できるはずです。しかし、geopandasの現行のstableバージョンである0.2.1はartistオブジェクトにアクセスしにくい作りになってます。そこで、アニメーションをするなら次のstableバージョンがでるまでの間は以下のようにgithubの最新のソースコードからインストールするのがお勧めです。

pip install -U git+https://github.com/geopandas/geopandas/

使用するデータ

今回は東京23区の人口比率の推移を可視化します(地理データ関連では、実際に処理を行うより、データを準備するところが大変だったりします)。

地形データはJapanCityGeoJson 2016からtokyo23.jsonというgeojsonファイルをダウンロードしています。

人口データはWikipedia:東京都区部のデータを再構成したファイルを23population.csvという名前で作成しました。

アニメーション

では実際にアニメーションを実行してみましょう。以下がコードになります。

import geopandas as gpd

df = pd.read_csv('23population.csv')
geodf = gpd.read_file('tokyo23.json').dissolve(by="id").sort_index()
years = np.sort(np.unique(df.year.values))

df という変数に人口データ、geodfという変数に地形データを読み込んでいます。

from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
ims = []
def update_fig(year):
    if len(ims) > 0:
        ims[0].remove()
        del ims[0]
    geos = geodf['geometry'].values
    sum = np.sum(df[(df.year==year)].sort_values(by='city').population)
    population_rates = df[(df.year==year)].sort_values(by='city').population/sum
    artist = gpd.plotting.plot_polygon_collection(ax, geos, population_rates, True, cmap="Reds")
    ims.append(artist)
    ax.set_title('year = ' + str(year))
    return ims
anim = FuncAnimation(fig, update_fig, interval=1000, repeat_delay=3000, frames=years)
fig.show()

artistオブジェクトの取得のため、地形データの描画は gpd.GeoDataFrame.plot ではなくその中で呼ばれている gpd.plotting.plot_polygon_collection という関数を呼び出しています。

tokyo23.gif

参考リンク

17
18
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
17
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?