質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

2回答

10598閲覧

離散的な観測点データから2次元grid作成 綺麗に内挿したい

shiroikuma

総合スコア11

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

1クリップ

投稿2018/08/10 07:49

離散的な観測点データから2次元gridデータへ変換をしたのですが、
もっと見た目を綺麗にしたいです。

試してみたこと
griddata.py で定義された方法で、x,y,z をgrid化しました。
grid の値は、griddata.pyのsizeで定義された範囲で取得される点の中央値(median)を返しています。

python

1#!/usr/bin/env python 2 3 4import pandas as pd 5import griddata 6import numpy as np 7import sys 8import matplotlib.pyplot as plt 9from mpl_toolkits.basemap import Basemap, maskoceans 10df = pd.read_csv(sys.argv[1]) 11 12#filter 13pm10 = df[(df.pm10 != "-")] 14# データの準備 15X = pm10.lon.values.astype(np.float32) 16Y = pm10.lat.values.astype(np.float32) 17Z = pm10.pm10.values.astype(np.float32) 18 19print(X.min(),X.max()) 20print(Y.min(),Y.max()) 21 22 23binsize = 0.01 24extent = (124.50,129.50,33.10,39.10) 25grid, bins, binloc,xi,yi = griddata.griddata(X, Y, Z, extent,binsize=binsize) # see this routine's docstring 26xx,yy = np.meshgrid(xi,yi) 27print(grid.shape) 28 29# minimum values for colorbar. filter our nans which are in the grid 30zmin = grid[np.where(np.isnan(grid) == False)].min() 31zmax = grid[np.where(np.isnan(grid) == False)].max() 32grid[np.isnan(grid)] = zmin 33grid = maskoceans(xx,yy,grid) 34bmap = Basemap(projection='cyl',llcrnrlon=124.50,urcrnrlon=129.50,llcrnrlat=33.10,urcrnrlat=39.10,resolution='i') 35 36bmap.imshow(grid, extent=extent,cmap=plt.cm.rainbow, origin='lower', vmin=0, vmax=zmax, aspect='auto') 37bmap.drawcoastlines(linewidth=0.3, linestyle='solid', color='black') 38bmap.drawcountries(linewidth=0.3, linestyle='solid', color='black') 39bmap.drawparallels(np.arange(-100, 90.0, 1.0), linewidth=0.1, color='black') 40bmap.drawmeridians(np.arange(0.0, 360.0, 1.0), linewidth=0.1, color='black') 41plt.colorbar() # draw colorbar 42plt.scatter(X,Y,marker='o',c='b',s=5) 43plt.title('Obs.Analysis TEST grid=0.01') 44#plt.show() 45plt.savefig("obs_grid_0p01.png",bbox_inches='tight')

python

1# griddata.py - 2010-07-11 ccampo 2import numpy as np 3 4def griddata(x, y, z, extent,binsize=0.01, retbin=True, retloc=True): 5 """ 6 Place unevenly spaced 2D data on a grid by 2D binning (nearest 7 neighbor interpolation). 8 9 Parameters 10 ---------- 11 x : ndarray (1D) 12 The idependent data x-axis of the grid. 13 y : ndarray (1D) 14 The idependent data y-axis of the grid. 15 z : ndarray (1D) 16 The dependent data in the form z = f(x,y). 17 binsize : scalar, optional 18 The full width and height of each bin on the grid. If each 19 bin is a cube, then this is the x and y dimension. This is 20 the step in both directions, x and y. Defaults to 0.01. 21 retbin : boolean, optional 22 Function returns `bins` variable (see below for description) 23 if set to True. Defaults to True. 24 retloc : boolean, optional 25 Function returns `wherebins` variable (see below for description) 26 if set to True. Defaults to True. 27 28 Returns 29 ------- 30 grid : ndarray (2D) 31 The evenly gridded data. The value of each cell is the median 32 value of the contents of the bin. 33 bins : ndarray (2D) 34 A grid the same shape as `grid`, except the value of each cell 35 is the number of points in that bin. Returns only if 36 `retbin` is set to True. 37 wherebin : list (2D) 38 A 2D list the same shape as `grid` and `bins` where each cell 39 contains the indicies of `z` which contain the values stored 40 in the particular bin. 41 42 Revisions 43 --------- 44 2010-07-11 ccampo Initial version 45 """ 46 # get extrema values. 47 #xmin, xmax = x.min(), x.max() 48 #ymin, ymax = y.min(), y.max() 49 xmin,xmax = extent[0],extent[1] 50 ymin,ymax = extent[2],extent[3] 51 # make coordinate arrays. 52 xo = np.arange(xmin, xmax+binsize, binsize) 53 yo = np.arange(ymin, ymax+binsize, binsize) 54 xi, yi = np.meshgrid(xo,yo) 55 56 # make the grid. 57 grid = np.zeros(xi.shape, dtype=x.dtype) 58 nrow, ncol = grid.shape 59 if retbin: bins = np.copy(grid) 60 61 # create list in same shape as grid to store indices 62 if retloc: 63 wherebin = np.copy(grid) 64 wherebin = wherebin.tolist() 65 66 # fill in the grid. 67 for row in range(nrow): 68 for col in range(ncol): 69 xc = xi[row, col] # x coordinate. 70 yc = yi[row, col] # y coordinate. 71 72 # find the position that xc and yc correspond to. 73 posx = np.abs(x - xc) 74 posy = np.abs(y - yc) 75 size = 0.5 76 #ibin = np.logical_and(posx < binsize/2., posy < binsize/2.) 77 ibin = np.logical_and(posx < size/2., posy < size/2.) 78 ind = np.where(ibin == True)[0] 79 80 # fill the bin. 81 bin = z[ibin] 82 if retloc: wherebin[row][col] = ind 83 if retbin: bins[row, col] = bin.size 84 if bin.size != 0: 85 binval = np.median(bin) 86 grid[row, col] = binval 87 else: 88 grid[row, col] = np.nan # fill empty bins with nans. 89 90 # return the grid 91 if retbin: 92 if retloc: 93# return grid, bins, wherebin 94 return grid, bins, wherebin,xo,yo 95 else: 96 return grid, bins 97 else: 98 if retloc: 99 return grid, wherebin 100 else: 101 return grid

griddata.py size=0.5 の場合
griddata.py size=0.5 の場合
griddata.py size=1.0 の場合
griddata.py size=1.0 の場合

です。
なんとなく良さげにできたんですけど、sizeを大きくしてその中央値をとると
当たり前ですが、平均化されてしまいます。
これに、中央値ではなく、距離による重み付けなどをしてメリハリつけてもっと綺麗に
内挿できればいいと考えています。

どなたかアドバイスいただければ幸いです。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

hayataka2049

2018/08/10 10:36 編集

なにか学術的な用途に使う図なのかなと思いますが、勝手に内挿しちゃっていいんですか?
shiroikuma

2018/08/20 00:00

夏季休暇で返答遅れました。本件は学術的に使うものではなく、面的なデータが必要で、いくつかパターンを作成するのが目的です。内挿方法を数種試してみたい、というのが本件の趣旨です。
guest

回答2

0

使用経験がないので不確かですが、scipy.interpolate.griddataを使うといいかもしれません。

sampleコードを見つけましたので、確認してください

https://scipython.com/book/chapter-8-scipy/examples/two-dimensional-interpolation-with-scipyinterpolategriddata/

投稿2018/08/10 23:00

R.Shigemori

総合スコア3376

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

自己解決

https://stackoverflow.com/questions/3104781/inverse-distance-weighted-idw-interpolation-with-python

こちらに投稿するのが遅くなりましたがこちら解決済みです。
調べたところ、IDW法を使い離散的な点を内装する手法がいいとのことで
こちらを採用しました。
他に、rbf,krikingの方法もありましたが、検証した結果、観測値点場所、観測地点数
よりIDW法を採用しました。
ありがとうございました。
イメージ説明

投稿2019/06/27 09:01

shiroikuma

総合スコア11

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問