forked from simpeg/simpeg
-
Notifications
You must be signed in to change notification settings - Fork 1
/
PlotUtils.py
235 lines (206 loc) · 8.02 KB
/
PlotUtils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import numpy as np
from scipy.interpolate import LinearNDInterpolator, NearestNDInterpolator
import matplotlib.pyplot as plt
def plot2Ddata(
xyz, data, vec=False, nx=100, ny=100,
ax=None, mask=None, level=False, figname=None,
ncontour=10, dataloc=False, contourOpts={},
levelOpts={}, scale="linear", clim=None,
method='linear'
):
"""
Take unstructured xy points, interpolate, then plot in 2D
:param numpy.array xyz: data locations
:param numpy.array data: data values
:param bool vec: plot streamplot?
:param float nx: number of x grid locations
:param float ny: number of y grid locations
:param matplotlib.axes ax: axes
:param boolean numpy.array mask: mask for the array
:param boolean level: boolean to plot (or not)
:meth:`matplotlib.pyplot.contour`
:param string figname: figure name
:param float ncontour: number of :meth:`matplotlib.pyplot.contourf`
contours
:param bool dataloc: plot the data locations
:param dict controuOpts: :meth:`matplotlib.pyplot.contourf` options
:param dict levelOpts: :meth:`matplotlib.pyplot.contour` options
:param numpy.array clim: colorbar limits
:param str method: interpolation method, either 'linear' or 'nearest'
"""
# Error checking and set vmin, vmax
vmin = None
vmax = None
if clim is not None:
vmin = np.min(clim)
vmax = np.max(clim)
for key, attr in zip(["vmin", "vmax"], [vmin, vmax]):
if key in contourOpts.keys():
if attr is None:
attr = contourOpts.pop(key)
else:
if not np.isclose(contourOpts[key], attr):
raise Exception(
"The values provided in the colorbar limit, clim {} "
"does not match the value of {} provided in the "
"contourOpts: {}. Only one value should be provided or "
"the two values must be equal.".format(
attr, key, contourOpts[key]
)
)
contourOpts.pop(key)
# create a figure if it doesn't exist
if ax is None:
fig = plt.figure()
ax = plt.subplot(111)
# interpolate data to grid locations
xmin, xmax = xyz[:, 0].min(), xyz[:, 0].max()
ymin, ymax = xyz[:, 1].min(), xyz[:, 1].max()
x = np.linspace(xmin, xmax, nx)
y = np.linspace(ymin, ymax, ny)
X, Y = np.meshgrid(x, y)
xy = np.c_[X.flatten(), Y.flatten()]
if vec is False:
if method == 'nearest':
F = NearestNDInterpolator(xyz[:, :2], data)
else:
F = LinearNDInterpolator(xyz[:, :2], data)
DATA = F(xy)
DATA = DATA.reshape(X.shape)
if scale == "log":
DATA = np.log10(abs(DATA))
# Levels definitions
dataselection = np.logical_and(
~np.isnan(DATA),
np.abs(DATA) != np.inf
)
# set vmin, vmax if they are not already set
vmin = DATA[dataselection].min() if vmin is None else vmin
vmax = DATA[dataselection].max() if vmax is None else vmax
if scale == "log":
if vmin <= 0 or vmax <= 0:
raise Exception(
"All values must be strictly positive in order to use the log-scale"
)
vmin = np.log10(vmin)
vmax = np.log10(vmax)
vstep = np.abs((vmin-vmax)/(ncontour+1))
levels = np.arange(vmin, vmax+vstep, vstep)
if DATA[dataselection].min() < levels.min():
levels = np.r_[DATA[dataselection].min(), levels]
if DATA[dataselection].max() > levels.max():
levels = np.r_[levels, DATA[dataselection].max()]
if mask is not None:
Fmask = NearestNDInterpolator(xyz[:, :2], mask)
MASK = Fmask(xy)
MASK = MASK.reshape(X.shape)
DATA = np.ma.masked_array(DATA, mask=MASK)
cont = ax.contourf(
X, Y, DATA, levels=levels, vmin=vmin, vmax=vmax,
**contourOpts
)
if level:
CS = ax.contour(X, Y, DATA, levels=levels, **levelOpts)
else:
# Assume size of data is (N,2)
datax = data[:, 0]
datay = data[:, 1]
if method == 'nearest':
Fx = NearestNDInterpolator(xyz[:, :2], datax)
Fy = NearestNDInterpolator(xyz[:, :2], datay)
else:
Fx = LinearNDInterpolator(xyz[:, :2], datax)
Fy = LinearNDInterpolator(xyz[:, :2], datay)
DATAx = Fx(xy)
DATAy = Fy(xy)
DATA = np.sqrt(DATAx**2+DATAy**2).reshape(X.shape)
DATAx = DATAx.reshape(X.shape)
DATAy = DATAy.reshape(X.shape)
if scale == "log":
DATA = np.log10(abs(DATA))
# Levels definitions
dataselection = np.logical_and(
~np.isnan(DATA),
np.abs(DATA) != np.inf
)
# set vmin, vmax
vmin = DATA[dataselection].min() if vmin is None else vmin
vmax = DATA[dataselection].max() if vmax is None else vmax
if scale == "log":
if vmin <= 0 or vmax <= 0:
raise Exception(
"All values must be strictly positive in order to use the log-scale"
)
vmin = np.log10(vmin)
vmax = np.log10(vmax)
vstep = np.abs((vmin-vmax)/(ncontour+1))
levels = np.arange(vmin, vmax+vstep, vstep)
if DATA[dataselection].min() < levels.min():
levels = np.r_[DATA[dataselection].min(), levels]
if DATA[dataselection].max() > levels.max():
levels = np.r_[levels, DATA[dataselection].max()]
if mask is not None:
Fmask = NearestNDInterpolator(xyz[:, :2], mask)
MASK = Fmask(xy)
MASK = MASK.reshape(X.shape)
DATA = np.ma.masked_array(DATA, mask=MASK)
cont = ax.contourf(
X, Y, DATA, levels=levels,
vmin=vmin, vmax=vmax,
**contourOpts
)
ax.streamplot(X, Y, DATAx, DATAy, color="w")
if level:
CS = ax.contour(X, Y, DATA, levels=levels, **levelOpts)
if dataloc:
ax.plot(xyz[:, 0], xyz[:, 1], 'k.', ms=2)
plt.gca().set_aspect('equal', adjustable='box')
if figname:
plt.axis("off")
fig.savefig(figname, dpi=200)
if level:
return cont, ax, CS
else:
return cont, ax
def plotLayer(sig, LocSigZ, xscale='log', ax=None,
showlayers=False, xlim=None, **kwargs):
"""Plot a layered earth model"""
sigma = np.repeat(sig, 2, axis=0)
z = np.repeat(LocSigZ[1:], 2, axis=0)
z = np.r_[LocSigZ[0], z, LocSigZ[-1]]
if xlim is None:
sig_min = sig.min()*0.5
sig_max = sig.max()*2
else:
sig_min, sig_max = xlim
if xscale == 'linear' and sig.min() == 0.:
if xlim is None:
sig_min = -sig.max()*0.5
sig_max = sig.max()*2
if ax is None:
plt.xscale(xscale)
plt.xlim(sig_min, sig_max)
plt.ylim(z.min(), z.max())
plt.xlabel('Conductivity (S/m)', fontsize=14)
plt.ylabel('Depth (m)', fontsize=14)
plt.ylabel('Depth (m)', fontsize=14)
if showlayers is True:
for locz in LocSigZ:
plt.plot(
np.linspace(sig_min, sig_max, 100),
np.ones(100)*locz, 'b--', lw=0.5
)
return plt.plot(sigma, z, 'k-', **kwargs)
else:
ax.set_xscale(xscale)
ax.set_xlim(sig_min, sig_max)
ax.set_ylim(z.min(), z.max())
ax.set_xlabel('Conductivity (S/m)', fontsize=14)
ax.set_ylabel('Depth (m)', fontsize=14)
if showlayers is True:
for locz in LocSigZ:
ax.plot(
np.linspace(sig_min, sig_max, 100),
np.ones(100)*locz, 'b--', lw=0.5
)
return ax.plot(sigma, z, 'k-', **kwargs)