-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcorrplotg.m
451 lines (323 loc) · 11.7 KB
/
corrplotg.m
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
function varargout = corrplotg(X,grp,clr,sym,varargin)
%CORRPLOTG Plot variable correlations and allowing multiple group
% data visualization
% It is a modification of original corplot function whis is a part of the Econometrics Toolbox
%
% Syntax:
%
% corrplotg(X)
% corrplotg(X,param,val,...)
% [R,PValue] = corrplotg(...)
%
% Description:
%
% Creates a matrix of plots showing correlations among pairs of variables
% in X. Histograms of the variables appear along the matrix diagonal;
% scatter plots of variable pairs appear off-diagonal. The slopes of the
% least-squares reference lines in the scatter plots are equal to the
% displayed correlation coefficients.
%
% Input Arguments:
%
% X - numObs-by-numVars matrix or tabular array of numObs observations on
% numVars variables.
%
% Optional Input Parameter Name/Value Pairs:
%
% NAME VALUE
%
% 'type' String indicating the type of correlation coefficient to
% compute. Values are:
%
% 'Pearson' Pearson's linear correlation coefficient
%
% 'Kendall' Kendall's rank correlation coefficient (tau)
%
% 'Spearman' Spearman's rank correlation coefficient (rho)
%
% The default is 'Pearson'.
%
% 'rows' String indicating how to treat NaN values in the data.
% Values are:
%
% 'all' Use all rows, regardless of NaNs
%
% 'complete' Use only rows with no NaNs
%
% 'pairwise' Use rows with no NaNs in column i or j to
% compute R(i,j)
%
% The default is 'pairwise'.
%
% 'tail' String indicating the alternative hypothesis Ha used to
% compute the PValue output. Values are:
%
% 'both' Ha: Correlation is not zero
%
% 'right' Ha: Correlation is greater than zero
%
% 'left' Ha: Correlation is less than zero
%
% The default is 'both'.
%
% 'varNames' Cell vector of variable name strings of length numVars to
% be used in the plots. Names are truncated to the first five
% characters. The default for matrix X is {'var1','var2',...}.
% The default for dataset array X is X.Properties.VarNames.
%
% 'testR' String indicating whether or not to test for significant
% correlations and highlight them in red. Values are 'off'
% and 'on'. The default is 'off'.
%
% 'alpha' Scalar level for tests of correlation significance. Values
% must be between 0 and 1. The default value is 0.05.
%
% Output Arguments:
%
% R - numVars-by-numVars correlation matrix of X displayed in the plots.
%
% PValue - numVars-by-numVars matrix of p-values corresponding to
% elements of R, used to test the hypothesis of no correlation
% against the alternative of a nonzero correlation.
%
% Notes:
%
% o P-values for Pearson's correlation are computed by transforming the
% correlation to create a t statistic with numObs-2 degrees of freedom.
% The transformation is exact when X is normal. P-values for Kendall's
% and Spearman's rank correlations are computed using either the exact
% permutation distributions (for small sample sizes), or large-sample
% approximations. P-values for two-tailed tests are computed by
% doubling the more significant of the two one-tailed p-values.
%
% o Using the 'pairwise' option for the 'rows' parameter may return a
% correlation matrix that is not positive definite. The 'complete'
% option always returns a positive definite matrix, but in general the
% estimates are based on fewer observations.
%
% o Use the GNAME function to identify points in the plots.
%
% Example:
%
% load example_data.mat
% corrplotg(data)
%
% See also COLLINTEST, CORR, GNAME.
%
% Copyright 2012 The MathWorks, Inc.
%
% Original corrplot function modified by:
% Rene Labounek, PhD and Igor Nestrasil, MD, PhD
% Division of Clinical Behavioral Neuroscience, Department of Pediatrics, University of Minnesota
% Minneapolis, MN, USA
% contact emails: rene.labounek@gmail.com, rlaboune@umn.edu
% Last edits: 7th February 2020
% Handle dataset array inputs:
if isa(X,'dataset')
try
X = dataset2table(X);
catch
error(message('econ:corrplot:DataNotConvertible'))
end
end
% Parse inputs and set defaults:
parseObj = inputParser;
parseObj.addRequired('X',@XCheck);
parseObj.addParamValue('type','Pearson',@typeCheck);
parseObj.addParamValue('rows','pairwise',@rowsCheck);
parseObj.addParamValue('tail','both',@tailCheck);
parseObj.addParamValue('varNames',{},@varNamesCheck);
parseObj.addParamValue('testR','off',@testRCheck);
parseObj.addParamValue('alpha',0.05,@alphaCheck);
parseObj.parse(X,varargin{:});
X = parseObj.Results.X;
corrType = parseObj.Results.type;
whichRows = parseObj.Results.rows;
tail = parseObj.Results.tail;
varNames = parseObj.Results.varNames;
testRFlag = strcmpi(parseObj.Results.testR,'on');
alpha = parseObj.Results.alpha;
numVars = size(X,2);
% Create variable names:
if isempty(varNames)
if isa(X,'table')
varNames = X.Properties.VariableNames;
else
varNames = strcat({'var'},num2str((1:numVars)','%-u'));
end
else
if length(varNames) < numVars
error(message('econ:corrplot:VarNamesTooFew'))
elseif length(varNames) > numVars
error(message('econ:corrplot:VarNamesTooMany'))
end
end
% Truncate variable names to first five characters:
varNames = cellfun(@(s)[s,' '],varNames,'UniformOutput',false);
varNames = cellfun(@(s)s(1:5),varNames,'UniformOutput',false);
% Convert table to double for numeric processing:
if isa(X,'table')
try
X = table2array(X);
X = double(X);
catch
error(message('econ:corrplot:DataNotConvertible'))
end
end
% Compute plot information:
[R,PValue] = corr(X,'type',corrType,'rows',whichRows,'tail',tail);
Mu = nanmean(X);
Sigma = nanstd(X);
Z = bsxfun(@minus,X,Mu);
Z = bsxfun(@rdivide,Z,Sigma);
ZLims = [nanmin(Z(:)),nanmax(Z(:))];
% Basic plot:
figure('Tag','corrPlotFigure','Position',[100 100 1000 720])
[H,Ax,bigAx] = gplotmatrixg(X,[],grp,clr,sym,10,[],'hist',varNames,varNames);
% Format plot:
%set(H(logical(eye(numVars))),'EdgeColor','c') % nechci
sXlabels = get(Ax,'XLabel');
sYlabels = get(Ax,'YLabel');
set([sXlabels{:}],'FontWeight','bold','Color',[0 0 0.6])
set([sYlabels{:}],'FontWeight','bold','Color',[0 0 0.6])
%set(get(bigAx,'Title'),'String','{\bf Correlation Matrix}') % nechci
for i = 1:numVars
for j = 1:numVars
set(get(bigAx,'Parent'),'CurrentAxes',Ax(i,j))
% set(Ax(i,j),'XLim',Mu(j)+(1.1)*ZLims*Sigma(j),...
% 'YLim',Mu(i)+(1.1)*ZLims*Sigma(i))
axis normal
if i ~= j && j<i
xxdata = Ax(i,j).Children(1,1).XData;
yydata = Ax(i,j).Children(1,1).YData;
if size(Ax(i,j).Children,1) > 1
for lnid = 2:size(Ax(i,j).Children,1)
xxdata = [ xxdata Ax(i,j).Children(lnid,1).XData];
yydata = [ yydata Ax(i,j).Children(lnid,1).YData];
end
end
line_data = [xxdata; yydata];
line_data = sum(line_data);
xxdata(isnan(line_data))=[];
yydata(isnan(line_data))=[];
par = polyfit(xxdata,yydata,1);
Xlimits = get(gca,'XLim');
Ylimits = get(gca,'YLim');
Yvals = par(1).*Xlimits + par(2);
% Yvals = Yvals - mean(Yvals) + mean(Ylimits);
hold on
plot(Xlimits,Yvals,'-.','LineWidth',2,'Color',[80 80 80]/255)
hold off
xlim(Xlimits)
ylim(Ylimits)
% hls = lsline;
% set(hls,'Color','m','Tag','lsLines','LineWidth',5);
plotPos = get(Ax(i,j),'Position');
if testRFlag && (PValue(i,j) < alpha)
corrColor = 'r';
% corrColor = [255 128 0]/255;
else
corrColor = 'k';
% corrColor = [0.4 0.4 0.4];
end
annotation('textbox',plotPos,...
'String',num2str(R(i,j),'%3.2f'),...
'FontWeight','Bold',...
'Color',corrColor,...
'FontSize',10,...
'EdgeColor','none','Tag','corrCoefs')
end
if j > i
set(Ax(i,j),'Visible','off')
set(Ax(i,j).Children,'Visible','off')
end
set(gca,'FontSize',12)
pause(0.5)
end
end
nargoutchk(0,2);
if nargout > 0
varargout = {R,PValue};
end
%-------------------------------------------------------------------------
% Check input X
function OK = XCheck(X)
if ischar(X)
error(message('econ:corrplot:DataNonNumeric'))
elseif isempty(X)
error(message('econ:corrplot:DataUnspecified'))
elseif isvector(X)
error(message('econ:corrplot:DataIsVector'))
else
OK = true;
end
%-------------------------------------------------------------------------
% Check value of 'type' parameter
function OK = typeCheck(corrType)
if ~isvector(corrType)
error(message('econ:corrplot:CorrTypeNonVector'))
elseif isnumeric(corrType)
error(message('econ:corrplot:CorrTypeNumeric'))
elseif ~ismember(lower(corrType),{'pearson','kendall','spearman'})
error(message('econ:corrplot:CorrTypeInvalid'))
else
OK = true;
end
%-------------------------------------------------------------------------
% Check value of 'rows' parameter
function OK = rowsCheck(whichRows)
if ~isvector(whichRows)
error(message('econ:corrplot:RowsParamNonVector'))
elseif isnumeric(whichRows)
error(message('econ:corrplot:RowsParamNumeric'))
elseif ~ismember(lower(whichRows),{'all','complete','pairwise'})
error(message('econ:corrplot:RowsParamInvalid'))
else
OK = true;
end
%-------------------------------------------------------------------------
% Check value of 'tail' parameter
function OK = tailCheck(tail)
if ~isvector(tail)
error(message('econ:corrplot:TailParamNonVector'))
elseif isnumeric(tail)
error(message('econ:corrplot:TailParamNumeric'))
elseif ~ismember(lower(tail),{'both','right','left'})
error(message('econ:corrplot:TailParamInvalid'))
else
OK = true;
end
%-------------------------------------------------------------------------
% Check value of 'varNames' parameter
function OK = varNamesCheck(varNames)
if ~isvector(varNames)
error(message('econ:corrplot:VarNamesNonVector'))
elseif isnumeric(varNames) || (iscell(varNames) && any(cellfun(@isnumeric,varNames)))
error(message('econ:corrplot:VarNamesNumeric'))
else
OK = true;
end
%-------------------------------------------------------------------------
% Check value of 'testR' parameter
function OK = testRCheck(testR)
if ~isvector(testR)
error(message('econ:corrplot:testRNonVector'))
elseif isnumeric(testR)
error(message('econ:corrplot:testRNumeric'))
elseif ~ismember(lower(testR),{'off','on'})
error(message('econ:corrplot:testRInvalid'))
else
OK = true;
end
%-------------------------------------------------------------------------
% Check value of 'alpha' parameter
function OK = alphaCheck(alpha)
if ~isnumeric(alpha)
error(message('econ:corrplot:AlphaNonNumeric'))
elseif ~isscalar(alpha)
error(message('econ:corrplot:AlphaNonScalar'))
elseif alpha < 0 || alpha > 1
error(message('econ:corrplot:AlphaOutOfRange'))
else
OK = true;
end