-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathREADME.html
580 lines (494 loc) · 33.7 KB
/
README.html
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--
This HTML was auto-generated from MATLAB code.
To make changes, update the MATLAB code and republish this document.
--><title>contourfcmap.m: filled contour plot with precise colormap</title><meta name="generator" content="MATLAB 9.4"><link rel="schema.DC" href="http://purl.org/dc/elements/1.1/"><meta name="DC.date" content="2018-03-29"><meta name="DC.source" content="./readmeExtras/README.m"><style type="text/css">
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{margin:0;padding:0;border:0;outline:0;font-size:100%;vertical-align:baseline;background:transparent}body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}blockquote:before,blockquote:after,q:before,q:after{content:'';content:none}:focus{outine:0}ins{text-decoration:none}del{text-decoration:line-through}table{border-collapse:collapse;border-spacing:0}
html { min-height:100%; margin-bottom:1px; }
html body { height:100%; margin:0px; font-family:Arial, Helvetica, sans-serif; font-size:10px; color:#000; line-height:140%; background:#fff none; overflow-y:scroll; }
html body td { vertical-align:top; text-align:left; }
h1 { padding:0px; margin:0px 0px 25px; font-family:Arial, Helvetica, sans-serif; font-size:1.5em; color:#d55000; line-height:100%; font-weight:normal; }
h2 { padding:0px; margin:0px 0px 8px; font-family:Arial, Helvetica, sans-serif; font-size:1.2em; color:#000; font-weight:bold; line-height:140%; border-bottom:1px solid #d6d4d4; display:block; }
h3 { padding:0px; margin:0px 0px 5px; font-family:Arial, Helvetica, sans-serif; font-size:1.1em; color:#000; font-weight:bold; line-height:140%; }
a { color:#005fce; text-decoration:none; }
a:hover { color:#005fce; text-decoration:underline; }
a:visited { color:#004aa0; text-decoration:none; }
p { padding:0px; margin:0px 0px 20px; }
img { padding:0px; margin:0px 0px 20px; border:none; }
p img, pre img, tt img, li img, h1 img, h2 img { margin-bottom:0px; }
ul { padding:0px; margin:0px 0px 20px 23px; list-style:square; }
ul li { padding:0px; margin:0px 0px 7px 0px; }
ul li ul { padding:5px 0px 0px; margin:0px 0px 7px 23px; }
ul li ol li { list-style:decimal; }
ol { padding:0px; margin:0px 0px 20px 0px; list-style:decimal; }
ol li { padding:0px; margin:0px 0px 7px 23px; list-style-type:decimal; }
ol li ol { padding:5px 0px 0px; margin:0px 0px 7px 0px; }
ol li ol li { list-style-type:lower-alpha; }
ol li ul { padding-top:7px; }
ol li ul li { list-style:square; }
.content { font-size:1.2em; line-height:140%; padding: 20px; }
pre, code { font-size:12px; }
tt { font-size: 1.2em; }
pre { margin:0px 0px 20px; }
pre.codeinput { padding:10px; border:1px solid #d3d3d3; background:#f7f7f7; }
pre.codeoutput { padding:10px 11px; margin:0px 0px 20px; color:#4c4c4c; }
pre.error { color:red; }
@media print { pre.codeinput, pre.codeoutput { word-wrap:break-word; width:100%; } }
span.keyword { color:#0000FF }
span.comment { color:#228B22 }
span.string { color:#A020F0 }
span.untermstring { color:#B20000 }
span.syscmd { color:#B28C00 }
.footer { width:auto; padding:10px 0px; margin:25px 0px 0px; border-top:1px dotted #878787; font-size:0.8em; line-height:140%; font-style:italic; color:#878787; text-align:left; float:none; }
.footer p { margin:0px; }
.footer a { color:#878787; }
.footer a:hover { color:#878787; text-decoration:underline; }
.footer a:visited { color:#878787; }
table th { padding:7px 5px; text-align:left; vertical-align:middle; border: 1px solid #d6d4d4; font-weight:bold; }
table td { padding:7px 5px; text-align:left; vertical-align:top; border:1px solid #d6d4d4; }
</style></head><body><div class="content"><h1><tt>contourfcmap.m</tt>: filled contour plot with precise colormap</h1><!--introduction--><p>Author: Kelly Kearney</p><p>This repository includes the code for the <tt>contourfcmap.m</tt> Matlab function, along with all dependent functions required to run it.</p><p>This function creates a shaded contour map, similar to that created by the contourf function. However, the relationship between a contourf plot and its colormap (i.e. exactly which color corresponds to each contour interval), can often be confusing and inconsistent. This function instead allows the user to specify exactly which colors to use in each interval, and also to choose colors for regions that exceed the contour line limits.</p><!--/introduction--><h2>Contents</h2><div><ul><li><a href="#1">Getting started</a></li><li><a href="#2">Syntax</a></li><li><a href="#3">Description</a></li><li><a href="#4">Examples</a></li><li><a href="#7">The algorithms behind contourfcmap</a></li><li><a href="#16">Contributions</a></li></ul></div><h2 id="1">Getting started</h2><p><b>Prerequisites</b></p><p>This function requires Matlab R14 or later.</p><p><b>Downloading and installation</b></p><p>This code can be downloaded from <a href="https://github.com/kakearney/contourfcmap-pkg/">Github</a> or the <a href="http://www.mathworks.com/matlabcentral/fileexchange/29638">MatlabCentral File Exchange</a>. The File Exchange entry is updated daily from the GitHub repository.</p><p><b>Matlab Search Path</b></p><p>The following folders need to be added to your Matlab Search path (via <tt>addpath</tt>, <tt>pathtool</tt>, etc.):</p><pre class="language-matlab">contourfcmap-pkg/FEX-function_handle
contourfcmap-pkg/arclength
contourfcmap-pkg/contourcs
contourfcmap-pkg/contourfcmap
contourfcmap-pkg/distance2curve
contourfcmap-pkg/fillnan
contourfcmap-pkg/interparc
contourfcmap-pkg/minmax
contourfcmap-pkg/multiplepolyint
contourfcmap-pkg/parsepv
contourfcmap-pkg/pcolorbar
</pre><h2 id="2">Syntax</h2><pre class="language-matlab">contourfcmap(x,y,z,clev,cmap)
contourfcmap(x,y,z,clev,cmap, Name, Value)
h = contourfcmap(<span class="keyword">...</span><span class="comment">)</span>
</pre><h2 id="3">Description</h2><p><tt>contourfcmap(x,y,z,clev,cmap)</tt> plots a filled contour plot of the matrix <tt>z</tt> with coordinates <tt>x</tt> and <tt>y</tt>. <tt>z</tt> must be at least a 2x2 matrix; <tt>x</tt> and <tt>y</tt> can either be matrices defining the grid for <tt>z</tt>, or vectors that correspond to the column and row coordinates, respectively. <tt>clev</tt> is an n x 1 vector defining the contour line levels, and <tt>cmap</tt> is an n-1 x 1 colormap array defining the colors to be used between each of the contour levels.</p><p><tt>contourfcmap(x,y,z,clev,cmap, 'lo', lo)</tt> indicates the color value <tt>lo</tt> (a 1 x 3 RGB array) to be used for any region with data lower than the first contour level. Default is white.</p><p><tt>contourfcmap(x,y,z,clev,cmap, 'hi', hi)</tt> indicates the color value <tt>hi</tt> (a 1 x 3 RGB array) to be used for any region with data higher than the last contour level. Default is white.</p><p><tt>contourfcmap(x,y,z,clev,cmap, 'method', method)</tt> allows you to switch between the 'recolor' and 'calccontour' algorithms (see below for details). Default is 'recolor' (though I now recommend 'calccontour' for R2017b or later).</p><p><tt>contourfcmap(x,y,z,clev,cmap, 'cbarloc', cbarloc)</tt> adds a psuedo-colorbar using the colorbar location indicator <tt>cbarloc</tt>. Default is no colorbar.</p><p><tt>contourfcmap(x,y,z,clev,cmap, 'evencb', evencb)</tt> indicates whether to space the colors on the colorbar evenly (evencb = true) or to size them according to the clev values (evencb = false). Default is false.</p><p><tt>h = contourfcmap(...)</tt> returns a structure <tt>h</tt> whose fields hold the colorbar axis handle structure (<tt>h.cb</tt>, see <tt>pcolorbar.m</tt> for details), contour object (<tt>h.h</tt>), contour matrix (<tt>h.c</tt>), and patch object (<tt>h.p</tt>).</p><h2 id="4">Examples</h2><p>First we'll plot a contourf plot using the standard Matlab functions. Without labeling the contour lines, it's difficult to tell which values in the colorbar correspond to the color intervals in the contourf plot.</p><pre class="codeinput">count = 0;
<span class="comment">% Data</span>
[x,y] = meshgrid(linspace(0,1,100));
z = peaks(100);
clev = [-5 -3 -2:.5:2 3 5];
<span class="comment">% Set up axes</span>
h.fig = figure(<span class="string">'color'</span>, <span class="string">'w'</span>);
h.ax(1) = axes(<span class="string">'position'</span>, [0.05 0.25 0.425 0.5]);
h.ax(2) = axes(<span class="string">'position'</span>, [0.525 0.25 0.425 0.5]);
<span class="comment">% Plot</span>
axes(h.ax(1));
contourf(x,y,z,clev);
cb = colorbar(<span class="string">'eastoutside'</span>);
colormap(h.ax(1), jet);
title(h.ax(1), <span class="string">'contourf'</span>);
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_01.png" alt=""> <p>Using contourfcmap, we can set the colors explictly, so it's much easier to tell exactly which color corresponds to which value.</p><pre class="codeinput">axes(h.ax(2));
hc = contourfcmap(x,y,z,clev,jet(12), <span class="keyword">...</span>
<span class="string">'lo'</span>, [.8 .8 .8], <span class="keyword">...</span>
<span class="string">'hi'</span>, [.2 .2 .2], <span class="keyword">...</span>
<span class="string">'cbarloc'</span>, <span class="string">'eastoutside'</span>, <span class="keyword">...</span>
<span class="string">'method'</span>, <span class="string">'calccontour'</span>);
title(h.ax(2), <span class="string">'contourfcmap'</span>);
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_02.png" alt=""> <p>If you prefer, you can set the colorbar to show the contour intervals evenly-spaced, even if the values aren't.</p><pre class="codeinput">delete(hc.cb.cb);
delete(hc.cb.ax);
cla;
hc = contourfcmap(x,y,z,clev,jet(12), <span class="keyword">...</span>
<span class="string">'lo'</span>, [.8 .8 .8], <span class="keyword">...</span>
<span class="string">'hi'</span>, [.2 .2 .2], <span class="keyword">...</span>
<span class="string">'cbarloc'</span>, <span class="string">'eastoutside'</span>, <span class="keyword">...</span>
<span class="string">'method'</span>, <span class="string">'calccontour'</span>, <span class="keyword">...</span>
<span class="string">'evencb'</span>, true);
title(h.ax(2), <span class="string">'contourfcmap'</span>);
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_03.png" alt=""> <h2 id="7">The algorithms behind contourfcmap</h2><p>This function began its life as a very simple function back in 2010. At that time, it was just a wrapper around <tt>contourf</tt>. A contour object in Maltab circa 2010 was a combination of some lines (the contour lines) and some patches (the shaded regions), and my function just looped over those patches and assigned new colors to their CData properties.</p><p>Then the 2014b release came along, and with it, a complete overhaul of Matlab's graphics objects. Under these new second-generation handle graphics (i.e. HG2), contour objects became more complex. They now were composed of TriangleStrips, a low-level, mostly-undocumented graphics object that really wasn't designed to be tampered with.</p><p>I updated my function to repeat its old processes, looping over the contours and changing the colors. But those color changes weren't very permanent. Changing the colormap, adding a colorbar, and most frustratingly, printing figures to file (using anything that relies on the print command, including print, saveas, export_fig, etc) undoes it. My function was pretty useless if I couldn't get changes to stick.</p><p>So in 2014, I introduced a new algorithm to contourfcmap, the 'calccontour' method. This version still uses the contour function to do the heavy lifting of the contouring calculations (contouring is hard!), but then tries to draw the shaded region using patches, as in the old HG1 version. I originally considered this just a hacky stand-in until I could get recoloring to stick. It worked pretty well for simple datasets, but fell apart for more complicated ones, especially those involving NaNs and non-cartesian grids. But the recoloring option reset issue has persisted through newer releases of Matlab (actually, it's gotten worse).</p><p>I've now (March 2018) just completed an overhaul of the calccontour option. This update may break back-compatibility with older code that uses contourfcmap, since I've modified some of the output variables (though it should still support all the older syntax in terms of input variables). I've expanded the code to be much more robust to non-cartesian grids and NaNs, and with the introduction of polyshape objects, the polygon calculations no longer require the Mapping Toolbox. Though still a bit slow to plot, this algorithm also fixes a few issues with the way Matlab colors (or rather, doesn't color) lower-than-lowest-contour regions. And finally, I've altered the colorbar code to rely on my pcolorbar function, which provides for more robust resizing (similar to a real colorbar) when one makes changes to the axis.</p><p>This example walks you through my thought process with this algorithm, and some of the issues with contourf that I'm trying to address.</p><p>We'll start with the peaks data:</p><pre class="codeinput">close <span class="string">all</span>;
figure;
[x,y,z] = peaks;
hs = scatter(x(:),y(:),10,z(:),<span class="string">'filled'</span>);
hcb = colorbar;
set(gca, <span class="string">'clim'</span>, [-15 15], <span class="string">'xlim'</span>, [-4.5 4.5], <span class="string">'ylim'</span>, [-4.5 4.5]);
hold <span class="string">on</span>;
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_04.png" alt=""> <p>Most of Matlab's example contour data assumes a cartesian grid (i.e. data aligned along the x- and y-axes, like an image). But it doesn't need to be... any structured grid will work. Let's add some skew and rotation, to make sure this example covers the more complicated cases:</p><pre class="codeinput">y = y + sin(x);
th = pi/3;
R = [cos(th) -sin(th); sin(th) cos(th)];
xy = R * [x(:) y(:)]';
x = reshape(xy(1,:), size(x));
y = reshape(xy(2,:), size(y));
delete(hs);
hs = scatter(x(:),y(:),10,z(:),<span class="string">'filled'</span>);
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_05.png" alt=""> <p>Contour data can also include NaNs. Sometimes these represent a missing data point or two. But they can also occur in bigger blocks; for example, a map of ocean data might represent land with NaNs. We'll add both enclosed (surrounded by data) and unenclosed (connecting to side of grid) NaNs, and make sure we have some extra data islands of high and low data in there too (you'll see why in a bit):</p><pre class="codeinput">z(z < 0.2 & z > 0) = NaN;
z(1:3,1:3) = -15;
z(end-3:end,end-3:end) = 15;
z(25:30, 1:2) = -15;
delete(hs);
hs = scatter(x(:),y(:),10,z(:),<span class="string">'filled'</span>);
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_06.png" alt=""> <p>Let's say we want to plot some contours, with specific colors between each interval. We can show this by plotting a scatter plot of the discretized values:</p><pre class="codeinput"><span class="comment">% Discretize</span>
bin = discretize(z, clev);
bin(z < clev(1)) = 0;
bin(z > clev(end)) = length(clev)+1;
<span class="comment">% Colors</span>
clev = [-5 -3 -2:.5:2 3 5];
cmap = [<span class="keyword">...</span>
0.65098 0.80784 0.8902
0.12157 0.47059 0.70588
0.69804 0.87451 0.54118
0.2 0.62745 0.17255
0.98431 0.60392 0.6
0.8902 0.10196 0.1098
0.99216 0.74902 0.43529
1 0.49804 0
0.79216 0.69804 0.83922
0.41569 0.23922 0.60392
1 1 0.6
0.69412 0.34902 0.15686];
lo = [0.57255 0.58431 0.56863];
hi = [0.84706 0.86275 0.83922];
<span class="comment">% Plot</span>
delete(hs);
hs = scatter(x(:),y(:),10,bin(:),<span class="string">'filled'</span>);
colormap([lo; cmap; hi]);
set(gca, <span class="string">'clim'</span>, [-0.5 length(clev)+0.5]);
tklabel = [<span class="string">'lo'</span> <span class="keyword">...</span>
arrayfun(@(a,b) sprintf(<span class="string">'%.1f - %.1f'</span>,a,b), <span class="keyword">...</span>
clev(1:end-1), clev(2:end), <span class="string">'uni'</span>, 0) <span class="keyword">...</span>
<span class="string">'hi'</span>];
set(hcb, <span class="string">'ticks'</span>, 0:length(clev), <span class="string">'ticklabels'</span>, tklabel);
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_07.png" alt=""> <p>We can try to use the same discretization trick to try to get our desired filled contour plot.</p><pre class="codeinput">delete(hs);
[cc, hc] = contourf(x,y,bin,0.5:1:length(clev));
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_08.png" alt=""> <p>But that sacrifices the resolution of the contouring. We can also try fiddle with the colormap, trying to get the colors to match our contour levels. I do this via the <a href="https://www.mathworks.com/matlabcentral/fileexchange/28943-color-palette-tables---cpt--for-matlab">cptcmap</a> function.</p><pre class="codeinput">loval = clev(1) - (clev(end)-clev(1))*0.1;
hival = clev(end) + (clev(end)-clev(1))*0.1;
ctable = [[loval clev]' [lo;cmap;hi]*255 [clev hival]' [lo;cmap;hi]*255]';
fid = fopen(<span class="string">'cmaptemp.cpt'</span>, <span class="string">'wt'</span>);
fprintf(fid, <span class="string">'%.2f %.0f %.0f %.0f %.2f %.0f %.0f %.0f\n'</span>, ctable);
fclose(fid);
[cmap2, lims] = cptcmap(<span class="string">'cmaptemp'</span>);
delete(<span class="string">'cmaptemp.cpt'</span>);
delete(hc);
[cc, hc] = contourf(x,y,z,clev);
set(gca, <span class="string">'clim'</span>, lims);
colormap(cmap2);
set(hcb, <span class="string">'Ticks'</span>, clev, <span class="string">'TickLabelsMode'</span>, <span class="string">'auto'</span>);
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_09.png" alt=""> <p>That mostly works, with a few drawbacks. First, tweaking the colormap to look like it has uneven color intervals requires some manaul calculation. Even with cptcmap, you have to do some setup ahead of time. Also, if we add the scatter plot on top, we'll see a few issues:</p><pre class="codeinput">hs = scatter(x(:), y(:), 10, z(:), <span class="string">'filled'</span>);
set(hs, <span class="string">'markeredgecolor'</span>, <span class="string">'w'</span>);
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_10.png" alt=""> <p>Most of the regions match the dots... except where there should be dark gray contours, i.e. where the data is lower than the specified lowest contour. Depending on your Matlab version, when you run this, the enclosed circle on the right may or may not be shaded. In all Matlab versions, the unenclosed areas (the bits that hit up against the wall of the grid) are unshaded.</p><p>So this is where the extra calculations in contourfcmap come in handy:</p><pre class="codeinput">delete(hs);
delete(hc);
delete(hcb);
h = contourfcmap(x,y,z,clev,cmap, <span class="keyword">...</span>
<span class="string">'lo'</span>, lo, <span class="keyword">...</span>
<span class="string">'hi'</span>, hi, <span class="keyword">...</span>
<span class="string">'cbarloc'</span>, <span class="string">'eastoutside'</span>, <span class="keyword">...</span>
<span class="string">'method'</span>, <span class="string">'calccontour'</span>);
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_11.png" alt=""> <p>Verdict: It's slower than a simple contour plot. But it colors the patches properly, including the lower-than-lowest-contour regions. And there's no need to do any tricky colormap calculations. If your application needs extremely fast rendering, and the lower-than-lowest thing isn't a problem for you, you might be better off using one of the tricks above. Otherwise, contourfcmap should be the easier solution.</p><h2 id="16">Contributions</h2><p>Community contributions to this package are welcome!</p><p>To report bugs, please submit <a href="https://github.com/kakearney/contourfcmap-pkg/issues">an issue</a> on GitHub and include:</p><div><ul><li>your operating system</li><li>your version of Matlab and all relevant toolboxes (type <tt>ver</tt> at the Matlab command line to get this info)</li><li>code/data to reproduce the error or buggy behavior, and the full text of any error messages received</li></ul></div><p>Please also feel free to submit enhancement requests, or to send pull requests (via GitHub) for bug fixes or new features.</p><p>I do monitor the MatlabCentral FileExchange entry for any issues raised in the comments, but would prefer to track issues on GitHub.</p><p class="footer"><br><a href="https://www.mathworks.com/products/matlab/">Published with MATLAB® R2018a</a><br></p></div><!--
##### SOURCE BEGIN #####
%% |contourfcmap.m|: filled contour plot with precise colormap
% Author: Kelly Kearney
%
% This repository includes the code for the |contourfcmap.m| Matlab function,
% along with all dependent functions required to run it.
%
% This function creates a shaded contour map, similar to that created by
% the contourf function. However, the relationship between a contourf plot
% and its colormap (i.e. exactly which color corresponds to each contour
% interval), can often be confusing and inconsistent. This
% function instead allows the user to specify exactly which colors to use
% in each interval, and also to choose colors for regions that exceed the
% contour line limits.
%
%% Getting started
%
% *Prerequisites*
%
% This function requires Matlab R14 or later.
%
% *Downloading and installation*
%
% This code can be downloaded from <https://github.com/kakearney/contourfcmap-pkg/ Github>
% or the
% <http://www.mathworks.com/matlabcentral/fileexchange/29638
% MatlabCentral File Exchange>. The File Exchange entry is updated daily
% from the GitHub repository.
%
% *Matlab Search Path*
%
% The following folders need to be added to your Matlab Search path (via
% |addpath|, |pathtool|, etc.):
%
% contourfcmap-pkg/FEX-function_handle
% contourfcmap-pkg/arclength
% contourfcmap-pkg/contourcs
% contourfcmap-pkg/contourfcmap
% contourfcmap-pkg/distance2curve
% contourfcmap-pkg/fillnan
% contourfcmap-pkg/interparc
% contourfcmap-pkg/minmax
% contourfcmap-pkg/multiplepolyint
% contourfcmap-pkg/parsepv
% contourfcmap-pkg/pcolorbar
%% Syntax
%
% contourfcmap(x,y,z,clev,cmap)
% contourfcmap(x,y,z,clev,cmap, Name, Value)
% h = contourfcmap(...)
%% Description
%
% |contourfcmap(x,y,z,clev,cmap)| plots a filled contour plot of the matrix
% |z| with coordinates |x| and |y|. |z| must be at least a 2x2 matrix; |x|
% and |y| can either be matrices defining the grid for |z|, or vectors that
% correspond to the column and row coordinates, respectively. |clev| is an
% n x 1 vector defining the contour line levels, and |cmap| is an n-1 x 1
% colormap array defining the colors to be used between each of the contour
% levels.
%
% |contourfcmap(x,y,z,clev,cmap, 'lo', lo)| indicates the color value |lo|
% (a 1 x 3 RGB array) to be used for any region with data lower than the
% first contour level. Default is white.
%
% |contourfcmap(x,y,z,clev,cmap, 'hi', hi)| indicates the color value |hi|
% (a 1 x 3 RGB array) to be used for any region with data higher than the
% last contour level. Default is white.
%
% |contourfcmap(x,y,z,clev,cmap, 'method', method)| allows
% you to switch between the 'recolor' and 'calccontour' algorithms (see
% below for details). Default is 'recolor' (though I now recommend
% 'calccontour' for R2017b or later).
%
% |contourfcmap(x,y,z,clev,cmap, 'cbarloc', cbarloc)| adds a
% psuedo-colorbar using the colorbar location indicator |cbarloc|. Default
% is no colorbar.
%
% |contourfcmap(x,y,z,clev,cmap, 'evencb', evencb)| indicates whether to
% space the colors on the colorbar evenly (evencb = true) or to size them
% according to the clev values (evencb = false). Default is false.
%
% |h = contourfcmap(...)| returns a structure |h| whose fields hold the
% colorbar axis handle structure (|h.cb|, see |pcolorbar.m| for details),
% contour object (|h.h|), contour matrix (|h.c|), and patch object (|h.p|).
%% Examples
%
% First we'll plot a contourf plot using the standard Matlab functions.
% Without labeling the contour lines, it's difficult to tell which values
% in the colorbar correspond to the color intervals in the contourf plot.
count = 0;
% Data
[x,y] = meshgrid(linspace(0,1,100));
z = peaks(100);
clev = [-5 -3 -2:.5:2 3 5];
% Set up axes
h.fig = figure('color', 'w');
h.ax(1) = axes('position', [0.05 0.25 0.425 0.5]);
h.ax(2) = axes('position', [0.525 0.25 0.425 0.5]);
% Plot
axes(h.ax(1));
contourf(x,y,z,clev);
cb = colorbar('eastoutside');
colormap(h.ax(1), jet);
title(h.ax(1), 'contourf');
%%
% Using contourfcmap, we can set the colors explictly, so it's much easier
% to tell exactly which color corresponds to which value.
axes(h.ax(2));
hc = contourfcmap(x,y,z,clev,jet(12), ...
'lo', [.8 .8 .8], ...
'hi', [.2 .2 .2], ...
'cbarloc', 'eastoutside', ...
'method', 'calccontour');
title(h.ax(2), 'contourfcmap');
%%
% If you prefer, you can set the colorbar to show the contour intervals
% evenly-spaced, even if the values aren't.
delete(hc.cb.cb);
delete(hc.cb.ax);
cla;
hc = contourfcmap(x,y,z,clev,jet(12), ...
'lo', [.8 .8 .8], ...
'hi', [.2 .2 .2], ...
'cbarloc', 'eastoutside', ...
'method', 'calccontour', ...
'evencb', true);
title(h.ax(2), 'contourfcmap');
%% The algorithms behind contourfcmap
%
% This function began its life as a very simple function back in 2010. At
% that time, it was just a wrapper around |contourf|. A contour
% object in Maltab circa 2010 was a combination of some lines (the
% contour lines) and some patches (the shaded regions), and my function
% just looped over those patches and assigned new colors to their CData
% properties.
%
% Then the 2014b release came along, and with it, a complete overhaul of
% Matlab's graphics objects. Under these new second-generation handle
% graphics (i.e. HG2), contour objects became more complex. They now were
% composed of TriangleStrips, a low-level, mostly-undocumented graphics
% object that really wasn't designed to be tampered with.
%
% I updated my function to repeat its old processes, looping over the
% contours and changing the colors. But those color changes weren't very
% permanent. Changing the colormap, adding a colorbar, and most
% frustratingly, printing figures to file (using anything that relies on
% the print command, including print, saveas, export_fig, etc) undoes it.
% My function was pretty useless if I couldn't get changes to stick.
%
% So in 2014, I introduced a new algorithm to contourfcmap, the 'calccontour'
% method. This version still uses the contour function to do the heavy
% lifting of the contouring calculations (contouring is hard!), but then tries to draw the
% shaded region using patches, as in the old HG1 version. I originally
% considered this just a hacky stand-in until I could get recoloring to
% stick. It worked pretty well for simple datasets, but fell apart for
% more complicated ones, especially those involving NaNs and non-cartesian
% grids. But the recoloring option reset issue has persisted through newer
% releases of Matlab (actually, it's gotten worse).
%
% I've now (March 2018) just completed an overhaul of the calccontour
% option. This update may break back-compatibility with older code that
% uses contourfcmap, since I've modified some of the output variables
% (though it should still support all the older syntax in terms of input
% variables). I've expanded the code to be much more robust to non-cartesian
% grids and NaNs, and with the introduction of polyshape objects, the
% polygon calculations no longer require the Mapping Toolbox. Though still
% a bit slow to plot, this algorithm also fixes a few issues with the way
% Matlab colors (or rather, doesn't color) lower-than-lowest-contour
% regions. And finally, I've altered the colorbar code to rely on my
% pcolorbar function, which provides for more robust resizing (similar to a
% real colorbar) when one makes changes to the axis.
%
% This example walks you through my thought process with this algorithm,
% and some of the issues with contourf that I'm trying to address.
%
% We'll start with the peaks data:
close all;
figure;
[x,y,z] = peaks;
hs = scatter(x(:),y(:),10,z(:),'filled');
hcb = colorbar;
set(gca, 'clim', [-15 15], 'xlim', [-4.5 4.5], 'ylim', [-4.5 4.5]);
hold on;
%%
% Most of Matlab's example contour data assumes a cartesian grid (i.e. data
% aligned along the x- and y-axes, like an image). But it doesn't need to
% be... any structured grid will work. Let's add some skew and rotation, to
% make sure this example covers the more complicated cases:
y = y + sin(x);
th = pi/3;
R = [cos(th) -sin(th); sin(th) cos(th)];
xy = R * [x(:) y(:)]';
x = reshape(xy(1,:), size(x));
y = reshape(xy(2,:), size(y));
delete(hs);
hs = scatter(x(:),y(:),10,z(:),'filled');
%%
% Contour data can also include NaNs. Sometimes these represent a missing
% data point or two. But they can also occur in bigger blocks; for
% example, a map of ocean data might represent land with NaNs. We'll add
% both enclosed (surrounded by data) and unenclosed (connecting to side of
% grid) NaNs, and make sure we have some extra data islands of high and low
% data in there too (you'll see why in a bit):
z(z < 0.2 & z > 0) = NaN;
z(1:3,1:3) = -15;
z(end-3:end,end-3:end) = 15;
z(25:30, 1:2) = -15;
delete(hs);
hs = scatter(x(:),y(:),10,z(:),'filled');
%%
% Let's say we want to plot some contours, with specific colors between
% each interval. We can show this by plotting a scatter plot of the
% discretized values:
% Discretize
bin = discretize(z, clev);
bin(z < clev(1)) = 0;
bin(z > clev(end)) = length(clev)+1;
% Colors
clev = [-5 -3 -2:.5:2 3 5];
cmap = [...
0.65098 0.80784 0.8902
0.12157 0.47059 0.70588
0.69804 0.87451 0.54118
0.2 0.62745 0.17255
0.98431 0.60392 0.6
0.8902 0.10196 0.1098
0.99216 0.74902 0.43529
1 0.49804 0
0.79216 0.69804 0.83922
0.41569 0.23922 0.60392
1 1 0.6
0.69412 0.34902 0.15686];
lo = [0.57255 0.58431 0.56863];
hi = [0.84706 0.86275 0.83922];
% Plot
delete(hs);
hs = scatter(x(:),y(:),10,bin(:),'filled');
colormap([lo; cmap; hi]);
set(gca, 'clim', [-0.5 length(clev)+0.5]);
tklabel = ['lo' ...
arrayfun(@(a,b) sprintf('%.1f - %.1f',a,b), ...
clev(1:end-1), clev(2:end), 'uni', 0) ...
'hi'];
set(hcb, 'ticks', 0:length(clev), 'ticklabels', tklabel);
%%
% We can try to use the same discretization trick to try to get our desired
% filled contour plot.
delete(hs);
[cc, hc] = contourf(x,y,bin,0.5:1:length(clev));
%%
% But that sacrifices the resolution of the contouring. We can also try
% fiddle with the colormap, trying to get the colors to match our contour
% levels. I do this via the
% <https://www.mathworks.com/matlabcentral/fileexchange/28943-color-palette-tablesREPLACE_WITH_DASH_DASH-cptREPLACE_WITH_DASH_DASHfor-matlab cptcmap>
% function.
loval = clev(1) - (clev(end)-clev(1))*0.1;
hival = clev(end) + (clev(end)-clev(1))*0.1;
ctable = [[loval clev]' [lo;cmap;hi]*255 [clev hival]' [lo;cmap;hi]*255]';
fid = fopen('cmaptemp.cpt', 'wt');
fprintf(fid, '%.2f %.0f %.0f %.0f %.2f %.0f %.0f %.0f\n', ctable);
fclose(fid);
[cmap2, lims] = cptcmap('cmaptemp');
delete('cmaptemp.cpt');
delete(hc);
[cc, hc] = contourf(x,y,z,clev);
set(gca, 'clim', lims);
colormap(cmap2);
set(hcb, 'Ticks', clev, 'TickLabelsMode', 'auto');
%%
% That mostly works, with a few drawbacks. First, tweaking the colormap to
% look like it has uneven color intervals requires some manaul calculation.
% Even with cptcmap, you have to do some setup ahead of time. Also, if we
% add the scatter plot on top, we'll see a few issues:
hs = scatter(x(:), y(:), 10, z(:), 'filled');
set(hs, 'markeredgecolor', 'w');
%%
% Most of the regions match the dots... except where there should be dark
% gray contours, i.e. where the data is lower than the specified lowest
% contour. Depending on your Matlab version, when you run this, the
% enclosed circle on the right may or may not be shaded. In all Matlab
% versions, the unenclosed areas (the bits that hit up against the wall of
% the grid) are unshaded.
%
% So this is where the extra calculations in contourfcmap come in handy:
delete(hs);
delete(hc);
delete(hcb);
h = contourfcmap(x,y,z,clev,cmap, ...
'lo', lo, ...
'hi', hi, ...
'cbarloc', 'eastoutside', ...
'method', 'calccontour');
%%
% Verdict: It's slower than a simple contour plot. But it colors the
% patches properly, including the lower-than-lowest-contour regions. And
% there's no need to do any tricky colormap calculations. If your
% application needs extremely fast rendering, and the lower-than-lowest
% thing isn't a problem for you, you might be better off using one of the
% tricks above. Otherwise, contourfcmap should be the easier solution.
%% Contributions
%
% Community contributions to this package are welcome!
%
% To report bugs, please submit
% <https://github.com/kakearney/contourfcmap-pkg/issues an issue> on GitHub and
% include:
%
% * your operating system
% * your version of Matlab and all relevant toolboxes (type |ver| at the Matlab command line to get this info)
% * code/data to reproduce the error or buggy behavior, and the full text of any error messages received
%
% Please also feel free to submit enhancement requests, or to send pull
% requests (via GitHub) for bug fixes or new features.
%
% I do monitor the MatlabCentral FileExchange entry for any issues raised
% in the comments, but would prefer to track issues on GitHub.
%
##### SOURCE END #####
--></body></html>