3D サーフェスプロットにおけるカスタムヒルシェーディング

Beginner

This tutorial is from open-source community. Access the source code

はじめに

この実験では、Python の Matplotlib を使って 3D サーフェスプロットでカスタムヒルシェーディングをどのように使用するかを示します。ヒルシェーディングとは、3D プロットにおける奥行きと起伏の感覚を高めるために光と影を使うことです。カスタムヒルシェーディングをカスタマイズすることで、より視覚的に魅力的で情報に富んだプロットを作成できます。

VM のヒント

VM の起動が完了したら、左上隅をクリックしてノートブックタブに切り替え、Jupyter Notebook を使って練習しましょう。

時々、Jupyter Notebook が読み込み終了するまで数秒待つ必要がある場合があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。

学習中に問題に遭遇した場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。

データの読み込みとフォーマット

このステップでは、3D サーフェスプロット用のデータを読み込み、フォーマットします。「jacksboro_fault_dem.npz」と呼ばれるサンプルデータセットを使用します。

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cbook, cm
from matplotlib.colors import LightSource

## Load and format data
dem = cbook.get_sample_data('jacksboro_fault_dem.npz')
z = dem['elevation']
nrows, ncols = z.shape
x = np.linspace(dem['xmin'], dem['xmax'], ncols)
y = np.linspace(dem['ymin'], dem['ymax'], nrows)
x, y = np.meshgrid(x, y)

region = np.s_[5:50, 5:50]
x, y, z = x[region], y[region], z[region]

プロットの設定

このステップでは、3D サーフェスプロット用のプロットを設定します。ヒルシェーディングをカスタマイズするために、LightSource オブジェクトを使用します。

## Set up plot
fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))

ls = LightSource(270, 45)
## To use a custom hillshading mode, override the built-in shading and pass
## in the rgb colors of the shaded surface calculated from "shade".
rgb = ls.shade(z, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft')
surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=rgb,
                       linewidth=0, antialiased=False, shade=False)

plt.show()

ヒルシェーディングのカスタマイズ

このステップでは、組み込みのシェーディングを上書きし、「shade」から算出された陰影付きの表面の RGB 色を渡すことで、ヒルシェーディングをカスタマイズします。

## Set up plot
fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))

ls = LightSource(270, 45)
## To use a custom hillshading mode, override the built-in shading and pass
## in the rgb colors of the shaded surface calculated from "shade".
rgb = ls.shade(z, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft')
surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=rgb,
                       linewidth=0, antialiased=False, shade=False)

plt.show()

レビューと修正

コードをレビューし、必要な修正を行います。コードが正確で、十分にコメントが付いていることを確認します。

まとめ

この実験では、Python の Matplotlib を使って 3D サーフェスプロットでカスタムヒルシェーディングを使用する方法を学びました。ヒルシェーディングをカスタマイズすることで、視覚的に魅力的で情報に富んだプロットを作成することができました。