0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PyGMTにおいて異なるデータを異なる色で着色する

Posted at

はじめに

完全に自分の備忘録用なのであしからず。
matplotlibでは、データフレームのある列の値に対してスライスして描画すると勝手に色を変更してくれるが、pyGMTにはそんな便利機能がないため、以下の内容を修正して作成していきたい。

作成コード

座標データと何かしらの値を持つデータフレームを用意する。

import pandas as pd

data = {
    "latitude": [20.5, 22.1, 25.3, 30.0, 35.5, 40.0, 42.2, 45.8, 47.0, 50.0],  # 緯度: 20-50
    "longitude": [120.5, 125.0, 130.1, 135.5, 140.0, 145.2, 150.0, 155.3, 157.7, 160.0],  # 経度: 120-160
    "val": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  # 値: 1-10
}

df = pd.DataFrame(data)

PyGMTの設定

import pygmt

fig = pygmt.Figure()
fig.basemap(
    projection="M15c",  # メルカトル図法で15cm幅の図
    region=f"{120}/{160}/{15}/{48}",  # 表示する緯度経度幅
    map_scale=f"g{140}/{20}+c20+w{800}+f",
)
fig.coast(
    resolution="f",
    land="lightgray",
    frame=["ag", f'+t'],
    region=f"{120}/{160}/{15}/{48}",
)

dfをgeoDataFrameに変換

import geopandas as gpd

gdf = gpd.GeoDataFrame(
    df.drop(["longitude", "latitude"], axis=1),
    geometry=[
        Point((lon, lat))
        for (lon, lat) in zip(df["longitude"], df["latitude"])
    ],
)

うまくいかなかったコードはこちら

for val, group in gdf.groupby("val"):
    fig.plot(
        data=group,
        style="c0.2c",
    )

fig.show()

image.png

解決策

単純な方法を用いている。matplotlibのカラーマップから良い感じのものを選び、今回のvalの数で色を取得している

カラーマップは以下を参照
https://matplotlib.org/2.0.2/examples/color/colormaps_reference.html

import matplotlib.pyplot as plt
import matplotlib as mpl

uniq_vals=sorted(df["val"].unique())
num_colors = len(uniq_val)
colormap = plt.get_cmap("tab20", num_colors)  # カラーマップを生成
group_colors = {group: mpl.colors.rgb2hex(colormap(i)) for i, group in enumerate(uniq_vals)}

for group, color in group_colors.items():
    group_data = df[df["val"] == group]
    if len(group_data):
        fig.plot(
            data=group_data,
            style="c0.2c",
            fill=color,
        )

image.png

おわりに

PyGMTで適当な色に着色することが多かったので、一旦これで作成する。
調べればPyGMTないでも何かしらのモジュールがありそうではあるが...

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?