-
Notifications
You must be signed in to change notification settings - Fork 0
/
matlab2tikz.m
4411 lines (3724 loc) · 156 KB
/
matlab2tikz.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
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% =========================================================================
% *** FUNCTION matlab2tikz
% ***
% *** Convert figures to TikZ (using pgfplots) for inclusion in LaTeX
% *** documents.
% ***
% *** Workflow:
% *** 0.) Place this file in one of the MATLAB paths
% ** (for example the current directory).
% *** 1.) Create your 2D plot in MATLAB.
% *** 2.) Invoke matlab2tikz by
% ***
% *** >> matlab2tikz( 'test.tikz' );
% ***
% ***
% *** -------
% *** Note:
% *** -------
% *** This program is a rewrite on Paul Wagenaars' Matfig2PGF which
% *** itself uses pure PGF as output format <[email protected]>, see
% ***
% *** http://www.mathworks.com/matlabcentral/fileexchange/12962
% ***
% *** In an attempt to simplify and extend things, the idea for
% *** matlab2tikz has emerged. The goal is to provide the user with a
% *** clean interface between the very handy figure creation in MATLAB
% *** and the powerful means that TikZ with pgfplots has to offer.
% ***
% ***
% *** TODO: * tex(t) annotations
% *** * 3D plots
% ***
% =========================================================================
% ***
% *** Copyright (c) 2008--2010, Nico Schlömer <[email protected]>
% *** All rights reserved.
% ***
% *** Redistribution and use in source and binary forms, with or without
% *** modification, are permitted provided that the following conditions are
% *** met:
% ***
% *** * Redistributions of source code must retain the above copyright
% *** notice, this list of conditions and the following disclaimer.
% *** * Redistributions in binary form must reproduce the above copyright
% *** notice, this list of conditions and the following disclaimer in
% *** the documentation and/or other materials provided with the distribution
% ***
% *** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% *** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% *** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% *** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% *** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% *** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% *** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% *** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% *** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% *** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% *** POSSIBILITY OF SUCH DAMAGE.
% ***
% =========================================================================
function matlab2tikz( varargin )
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% define some global variables
clear global matlab2tikzName;
clear global matlab2tikzVersion;
clear global matlab2tikzAuthor;
clear global matlab2tikzAuthorEmail;
clear global matlab2tikzYears;
clear global tol;
clear global matlab2tikzOpts;
clear global currentHandles;
clear global tikzFileName;
clear global relativePngPath;
global matlab2tikzOpts;
global currentHandles;
global matlab2tikzName;
matlab2tikzName = 'matlab2tikz';
global matlab2tikzVersion;
matlab2tikzVersion = '0.0.5';
global matlab2tikzAuthor;
matlab2tikzAuthor = 'Nico Schlömer';
global matlab2tikzAuthorEmail;
matlab2tikzAuthorEmail = '[email protected]';
global matlab2tikzYears;
matlab2tikzYears = '2008--2010';
global tikzOptions; % for the arrow style -- TODO: see if we can get this removed
tikzOptions = cell(0);
global tol;
tol = 1e-15; % global round-off tolerance;
% used, for example, in equality test for doubles
global relativePngPath;
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% scan the options
matlab2tikzOpts = inputParser;
matlab2tikzOpts.addOptional( 'filename', ...
[], ...
@(x) filenameValidation(x,matlab2tikzOpts) );
% possibility to give a file handle file as argument
matlab2tikzOpts.addOptional( 'filehandle', [], @filehandleValidation );
% whether to strictly stick to the default MATLAB plot appearance:
matlab2tikzOpts.addOptional( 'strict', 0, @islogical );
% don't plot warning messages
matlab2tikzOpts.addOptional( 'silent', 0, @islogical );
% Whether to save images in PNG format or to natively draw filled squares
% using TikZ itself.
% Default it PNG.
matlab2tikzOpts.addOptional( 'imagesAsPng', 1, @islogical );
matlab2tikzOpts.addOptional( 'relativePngPath', [], @ischar );
% width and height of the figure
matlab2tikzOpts.addParamValue( 'height', [], @ischar );
matlab2tikzOpts.addParamValue( 'width' , [], @ischar );
% minimum distance for two points to be plotted separately
matlab2tikzOpts.addParamValue( 'minimumPointsDistance', 0.0, @isnumeric );
% extra axis options
matlab2tikzOpts.addParamValue( 'extraAxisOptions', {}, @isCellOrChar );
% file encoding
matlab2tikzOpts.addParamValue( 'encoding' , '', @ischar );
% math mode in titles and captions
% -- this is default "true" as MATLAB may put non-LaTeX compilable structures
% in there.
matlab2tikzOpts.addParamValue( 'mathmode' , 1, @islogical );
matlab2tikzOpts.parse( varargin{:} );
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% add extra elements
currentHandles.gca = gca;
currentHandles.gcf = gcf;
currentHandles.colormap = colormap;
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% handle output file handle/file name
if ~isempty( matlab2tikzOpts.Results.filehandle )
fid = matlab2tikzOpts.Results.filehandle;
fileWasOpen = 1;
if ~isempty(matlab2tikzOpts.Results.filename)
userWarning( 'File handle AND file name for output given. File handle used, file name discarded.')
end
else
fileWasOpen = 0;
% set filename
if ~isempty(matlab2tikzOpts.Results.filename)
filename = matlab2tikzOpts.Results.filename;
else
filename = uiputfile( {'*.tikz'; '*.*'}, ...
'Save File' );
end
% open the file for writing
fid = fopen( filename, ...
'w', ...
'native', ...
matlab2tikzOpts.Results.encoding ...
);
if fid == -1
error( 'matlab2tikz:fileOpenError', ...
'Unable to open file ''%s'' for writing.', ...
filename );
end
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
global tikzFileName;
tikzFileName = fopen( fid );
% By default, reference the PNG (if required) from the TikZ file
% as the file path of the TikZ file itself. This works if the MATLAB script
% is executed in the same folder where the TeX file sits.
if ( isempty(matlab2tikzOpts.Results.relativePngPath) )
relativePngPath = fileparts(tikzFileName);
else
relativePngPath = matlab2tikzOpts.Results.relativePngPath;
end
% print some version info to the screen
userWarning( [ '\nThis is %s v%s.\n' , ...
'The latest updates can be retrieved from\n\n', ...
' http://win.ua.ac.be/~nschloe/content/matlab2tikz/\n\n', ...
'and\n\n',...
' http://www.mathworks.com/matlabcentral/fileexchange/22022 .\n\n', ...
'where you can also make suggestions and rate %s.\n' ], ...
matlab2tikzName, matlab2tikzVersion, matlab2tikzName );
userWarning( [ 'matlab2tikz uses features of Pgfplots which may be available only in recent version.\n', ...
'Make sure you have at least Pgfplots 1.3 available.\n', ...
'For best results, use \\pgfplotsset{compat=newest}.\n' ] );
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Save the figure as pgf to file -- here's where the work happens
saveToFile( fid, fileWasOpen );
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
sprintf( '\nRemember to load \\usepackage{tikz} and \\usepackage{pgfplots} in the preamble of your LaTeX document.\n\n' );
% clean up
clear global matlab2tikzName;
clear global matlab2tikzVersion;
clear global matlab2tikzOpts;
clear global tol;
clear global currentHandles;
clear all;
% -----------------------------------------------------------------------
% validates the optional argument 'filename' to not be another
% another keyword
function l = filenameValidation( x, p )
l = ischar(x) && ~any( strcmp(x,p.Parameters) );
end
% -----------------------------------------------------------------------
% -----------------------------------------------------------------------
% validates the optional argument 'filehandle' to be the handle of
% an open file
function l = filehandleValidation( x, p )
l = isnumeric(x) && any( x==fopen('all') );
end
% -----------------------------------------------------------------------
% -----------------------------------------------------------------------
function l = isCellOrChar( x, p )
l = iscell(x) || ischar(x);
end
% -----------------------------------------------------------------------
end
% =========================================================================
% *** END OF FUNCTION matlab2tikz
% =========================================================================
% =========================================================================
% *** FUNCTION saveToFile
% ***
% *** Save the figure as TikZ to a file.
% *** All other routines are called from here.
% ***
% =========================================================================
function saveToFile( fid, fileWasOpen )
global matlab2tikzName
global matlab2tikzVersion
global matlab2tikzAuthor
global matlab2tikzAuthorEmail
global matlab2tikzYears
global matlab2tikzOpts
global currentHandles
global tikzOptions
global requiredRgbColors
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% enter plot recursion --
% It is important to turn hidden handles on, as visible lines (such as the
% axes in polar plots, for example), are otherwise hidden from their
% parental handles (and can hence not be discovered by matlab2tikz).
% With ShowHiddenHandles 'on', there is no escape. :)
set( 0, 'ShowHiddenHandles', 'on' );
% get all axes handles
fh = currentHandles.gcf;
axesHandles = findobj( fh, 'type', 'axes' );
% remove all legend handles as they are treated separately
rmList = [];
for k = 1:length(axesHandles)
if strcmp( get(axesHandles(k),'Tag'), 'legend' )
rmList = [ rmList, k ];
end
end
axesHandles(rmList) = [];
% Turn around the handles vector to make sure that plots that appeared
% first also appear first in the vector. This has effects on the alignment
% and the order in which the plots appear in the final TikZ file.
% In fact, this is not really important but makes things more 'natural'.
axesHandles = axesHandles(end:-1:1);
% find alignments
[visibleAxesHandles,alignmentOptions,ix] = alignSubPlots( axesHandles );
str = [];
for k = 1:length(visibleAxesHandles)
str = [ str, drawAxes(visibleAxesHandles(ix(k)),alignmentOptions(ix(k))) ];
end
set( 0, 'ShowHiddenHandles', 'off' );
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% actually print the stuff
fprintf( fid, [ '%% This file was created by %s v%s.\n', ...
'%% Copyright (c) %s, %s <%s>\n', ...
'%% All rights reserved.\n' ], ...
matlab2tikzName, matlab2tikzVersion, ...
matlab2tikzYears, matlab2tikzAuthor, matlab2tikzAuthorEmail );
if ~matlab2tikzOpts.Results.silent
fprintf( fid, [ '%%\n',...
'%% The latest updates can be retrieved from\n', ...
'%% http://win.ua.ac.be/~nschloe/content/matlab2tikz/\n', ...
'%% and\n',...
'%% http://www.mathworks.com/matlabcentral/fileexchange/22022 .\n', ...
'%% where you can also make suggestions and rate %s.\n\n' ], ...
matlab2tikzName );
else
fprintf( fid, '\n' );
end
if isempty(tikzOptions)
fprintf( fid, '\\begin{tikzpicture}\n' );
else
fprintf( fid, '\\begin{tikzpicture}[%s]\n', collapse(tikzOptions,',') );
end
% don't forget to define the colors
if size(requiredRgbColors,1)
fprintf( fid, '\n%% defining custom colors\n' );
end
for k = 1:size(requiredRgbColors,1)
fprintf( fid, '\\definecolor{mycolor%d}{rgb}{%g,%g,%g}\n', k, ...
requiredRgbColors(k,:) );
end
% print the content
fprintf( fid, '%s', str );
fprintf( fid, '\\end{tikzpicture}');
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% close the file if necessary
if ~fileWasOpen
fclose( fid );
end
end
% =========================================================================
% *** END OF FUNCTION saveToFile
% =========================================================================
% =========================================================================
% *** FUNCTION handleAllChildren
% ***
% *** Draw all children of a graphics object (if they need to be drawn).
% ***
% =========================================================================
function str = handleAllChildren( handle )
str = [];
children = get( handle, 'Children' );
% It's important that we go from back to front here, as this is
% how MATLAB does it, too. Significant for patch (contour) plots,
% and the order of plotting the colored patches.
for i = length(children):-1:1
child = children(i);
switch get( child, 'Type' )
case 'axes'
str = [ str, drawAxes( child ) ];
case 'line'
str = [ str, drawLine( child ) ];
case 'patch'
str = [ str, drawPatch( child ) ];
case 'image'
str = [ str, drawImage( child ) ];
case 'hggroup'
str = [ str, drawHggroup( child ) ];
case { 'hgtransform' }
% don't handle those directly but descend to its children
% (which could for example be patch handles)
str = [ str, handleAllChildren( child ) ];
case { 'uitoolbar', 'uimenu', 'uicontextmenu', 'uitoggletool',...
'uitogglesplittool', 'uipushtool', 'hgjavacomponent', ...
'text', 'surface' }
% TODO: text, surface
% TODO: bail out with warning in case of a 3D-plot (parameter plots!)
% don't to anything for these handles and its children
otherwise
error( 'matfig2tikz:handleAllChildren', ...
'I don''t know how to handle this object: %s\n', ...
get(child,'Type') );
end
end
end
% =========================================================================
% *** END OF FUNCTION handleAllChildren
% =========================================================================
% =========================================================================
% *** FUNCTION drawAxes
% ***
% *** Input arguments:
% *** handle.................The axes environment handle.
% *** alignmentOptions.......The alignment options as defined in the
% *** function `alignSubPlots()`.
% *** This argument is optional.
% ***
% =========================================================================
function str = drawAxes( handle, alignmentOptions )
global matlab2tikzOpts;
global currentHandles;
% Make the axis options a global variable as plot objects further below
% in the hierarchy might want to append something.
% One example is the required 'ybar stacked' option for stacked bar
% plots.
global axisOpts;
% pass on information about reversed axis (to drawImage)
global xAxisReversed;
global yAxisReversed;
% handle special cases
switch get(handle,'Tag')
case 'Colorbar'
% Handle a colorbar separately.
% Note how currentHandles.gca does *not* get updated; this fact is
% made use of in drawColorbar().
str = drawColorbar( handle, alignmentOptions );
return
case 'legend'
% Don't handle the legend here, but further below in the 'axis'
% environment.
% In MATLAB, an axes environment and it's corresponding legend are
% children of the same figure (siblings), while in pgfplots, the
% \legend (or \addlegendentry) command must appear within the axis
% environment.
return
otherwise
% continue as usual
end
% update gca
currentHandles.gca = handle;
str = [];
axisOpts = cell(0);
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get the axes dimensions
dim = getAxesDimensions( handle, ...
matlab2tikzOpts.Results.width, ...
matlab2tikzOpts.Results.height );
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if ~isVisible( handle )
% An invisible axes container *can* have visible children, so don't
% immediately bail out here.
c = get(handle,'Children');
containsVisibleChild = 0;
for k=1:length(c)
if isVisible( c(k) )
containsVisibleChild = 1;
break;
end
end
if containsVisibleChild
env = 'axis';
axisOpts = [ axisOpts, ...
'hide x axis, hide y axis', ...
sprintf('width=%g%s, height=%g%s', dim.x.value, dim.x.unit, ...
dim.y.value, dim.y.unit ), ...
'scale only axis' ];
str = plotAxisEnvironment( handle, env );
end
return
end
% add manually given extra axis options
extraAxisOptions = matlab2tikzOpts.Results.extraAxisOptions;
if ~isempty( extraAxisOptions )
axisOpts = [ axisOpts, ...
extraAxisOptions ];
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get scales
xScale = get( handle, 'XScale' );
yScale = get( handle, 'YScale' );
isXLog = strcmp( xScale, 'log' );
isYLog = strcmp( yScale, 'log' );
if ~isXLog && ~isYLog
env = 'axis';
elseif isXLog && ~isYLog
env = 'semilogxaxis';
elseif ~isXLog && isYLog
env = 'semilogyaxis';
else
env = 'loglogaxis';
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% set alignment options
if ~isempty(alignmentOptions.opts)
axisOpts = [ axisOpts, alignmentOptions.opts ];
end
% the following is general MATLAB behavior
axisOpts = [ axisOpts, 'scale only axis' ];
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% axis colors
xColor = get( handle, 'XColor' );
if ( any(xColor) ) % color not black [0,0,0]
col = getColor( handle, xColor, 'patch' );
axisOpts = [ axisOpts, ...
[ 'every outer x axis line/.append style={',col, '}' ], ...
[ 'every x tick label/.append style={font=\\color{',col,'}}'] ];
end
yColor = get( handle, 'YColor' );
if ( any(yColor) ) % color not black [0,0,0]
col = getColor( handle, yColor, 'patch' );
axisOpts = [ axisOpts, ...
[ 'every outer y axis line/.append style={',col, '}' ], ...
[ 'every y tick label/.append style={font=\\color{',col,'}}'] ];
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% background color
backgroundColor = get( handle, 'Color' );
if ~strcmp( backgroundColor, 'none' )
col = getColor( handle, backgroundColor, 'patch' );
if ~strcmp( col, 'white' )
axisOpts = [ axisOpts, ...
sprintf( 'axis background/.style={fill=%s}' , col ) ];
end
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% set the width
axisOpts = [ axisOpts, ...
sprintf( 'width=%g%s' , dim.x.value, dim.x.unit ) ];
axisOpts = [ axisOpts, ...
sprintf( 'height=%g%s' , dim.y.value, dim.y.unit ) ];
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% handle the orientation
xAxisReversed = 0;
if strcmp( get(handle,'XDir'), 'reverse' )
xAxisReversed = 1;
axisOpts = [ axisOpts, 'x dir=reverse' ];
end
xAxisReversed = 0;
if strcmp( get(handle,'YDir'), 'reverse' )
yAxisReversed = 1;
axisOpts = [ axisOpts, 'y dir=reverse' ];
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% for double axes pairs, unconditionally put the ordinate left for the
% first one, right for the second one.
if alignmentOptions.isElderTwin
axisOpts = [ axisOpts, 'axis y line=left', 'axis x line=bottom' ];
elseif alignmentOptions.isYoungerTwin
axisOpts = [ axisOpts, 'axis y line=right', 'axis x line=top' ];
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get axis limits
xLim = get( handle, 'XLim' );
yLim = get( handle, 'YLim' );
axisOpts = [ axisOpts, ...
sprintf('xmin=%g, xmax=%g', xLim ), ...
sprintf('ymin=%g, ymax=%g', yLim ) ];
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get ticks along with the labels
[ ticks, tickLabels ] = getTicks( handle );
if ~isempty( ticks.x )
axisOpts = [ axisOpts, ...
sprintf( 'xtick={%s}', ticks.x ) ];
end
if ~isempty( tickLabels.x )
axisOpts = [ axisOpts, ...
sprintf( 'xticklabels={%s}', tickLabels.x ) ];
end
if ~isempty( ticks.y )
axisOpts = [ axisOpts, ...
sprintf( 'ytick={%s}', ticks.y ) ];
end
if ~isempty( tickLabels.y )
axisOpts = [ axisOpts, ...
sprintf( 'yticklabels={%s}', tickLabels.y ) ];
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get axis labels
axisLabels = getAxisLabels( handle );
if ~isempty( axisLabels.x )
xlabelText = sprintf( '%s', escapeCharacters(axisLabels.x) );
if matlab2tikzOpts.Results.mathmode
xlabelText = [ '$' xlabelText '$' ];
end
axisOpts = [ axisOpts, ...
sprintf( 'xlabel={%s}', xlabelText ) ];
end
if ~isempty( axisLabels.y )
ylabelText = sprintf( '%s', escapeCharacters(axisLabels.y) );
if matlab2tikzOpts.Results.mathmode
ylabelText = [ '$' ylabelText '$' ];
end
axisOpts = [ axisOpts, ...
sprintf( 'ylabel={%s}', ylabelText ) ];
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get title
title = get( get( handle, 'Title' ), 'String' );
if ~isempty(title)
titleText = sprintf( '%s', escapeCharacters(title) );
if matlab2tikzOpts.Results.mathmode
titleText = [ '$' titleText '$' ];
end
axisOpts = [ axisOpts, ...
sprintf( 'title={%s}', titleText ) ];
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get grids
isGrid = 0;
if strcmp( get( handle, 'XGrid'), 'on' );
axisOpts = [ axisOpts, 'xmajorgrids' ];
isGrid = 1;
end
if strcmp( get( handle, 'XMinorGrid'), 'on' );
axisOpts = [ axisOpts, 'xminorgrids' ];
isGrid = 1;
end
if strcmp( get( handle, 'YGrid'), 'on' )
axisOpts = [ axisOpts, 'ymajorgrids' ];
isGrid = 1;
end
if strcmp( get( handle, 'YMinorGrid'), 'on' );
axisOpts = [ axisOpts, 'yminorgrids' ];
isGrid = 1;
end
% set the line style
if isGrid
matlabGridLineStyle = get( handle, 'GridLineStyle' );
% take over the grid line style in any case when in strict mode;
% if not, don't add anything in case of default line grid line style
% and effectively take pgfplots' default
defaultMatlabGridLineStyle = ':';
if matlab2tikzOpts.Results.strict ...
|| ~strcmp(matlabGridLineStyle,defaultMatlabGridLineStyle)
gls = translateLineStyle( matlabGridLineStyle );
str = [ str, ...
sprintf( '\n\\pgfplotsset{every axis grid/.style={style=%s}}\n\n', gls ) ];
end
else
% When specifying 'axis on top', the axes stay above all graphs (which is
% default MATLAB behavior), but so do the grids (which is not default
% behavior).
% To date (Dec 12, 2009) pgfplots is not able to handle those things
% separately.
% As a prelimary compromise, only pull this option if no grid is in use.
axisOpts = [ axisOpts, 'axis on top' ];
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% See if there are any legends that need to be plotted.
c = get( get(handle,'Parent'), 'Children' ); % siblings of this handle
% Since the legends are at the same level as axes in the hierarchy,
% we can't work out which relates to which using the tree
% so we have to do it by looking for a plot inside which the legend sits.
% This could be done better with a heuristic of finding
% the nearest legend to a plot, which would cope with legends outside
% plot boundaries.
% TODO: How to uniquely connect a legend with a pair of axes?
axisDims = get(handle,'Position');
axisLeft = axisDims(1);
axisBot = axisDims(2);
axisWid = axisDims(3);
axisHei = axisDims(4);
for k=1:size(c)
if strcmp( get(c(k),'Type'), 'axes' ) && ...
strcmp( get(c(k),'Tag' ), 'legend' )
legendHandle = c(k);
if (legendHandle)
legDims = get( legendHandle, 'Position' );
legLeft = legDims(1);
legBot = legDims(2);
legWid = legDims(3);
legHei = legDims(4);
if ( legLeft > axisLeft ...
&& legBot > axisBot ...
&& legLeft+legWid < axisLeft+axisWid ...
&& legBot+legHei < axisBot+axisHei )
axisOpts = [ axisOpts, ...
getLegendOpts( legendHandle ) ];
end
end
end
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% actually begin drawing
str = [ str, ...
plotAxisEnvironment( handle, env ) ];
% -----------------------------------------------------------------------
function str = plotAxisEnvironment( handle, env )
% First, run through all the children to give them the chance to
% contribute to 'axisOpts'.
childrenStr = handleAllChildren( handle );
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Format 'axisOpts' nicely.
opts = [ '\n', collapse( axisOpts, ',\n' ) ];
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% if a tag is given, use it as comment
tag = get(handle, 'tag');
if ~isempty(tag)
str = sprintf( '\n%% Axis "%s"', tag );
else
str = sprintf( '\n%% Axis at [%.2g %.2f %.2g %.2g]', ...
get(handle, 'position' ) );
end
% Now, return the whole axis environment.
str = [ str, ...
sprintf( ['\n\\begin{%s}[',opts,']\n\n'], env ), ...
childrenStr, ...
sprintf( '\\end{%s}\n\n', env ) ];
end
% -----------------------------------------------------------------------
end
% =========================================================================
% *** END OF FUNCTION drawAxes
% =========================================================================
% =========================================================================
% *** FUNCTION axisIsVisible
% =========================================================================
function bool = axisIsVisible( axisHandle )
if ~isVisible( axisHandle )
% An invisible axes container *can* have visible children, so don't
% immediately bail out here.
c = get(axisHandle,'Children');
bool = 0;
for k=1:length(c)
if isVisible( c(k) )
bool = 1;
return;
end
end
else
bool = true;
end
end
% =========================================================================
% *** END FUNCTION axisIsVisible
% =========================================================================
% =========================================================================
% *** FUNCTION drawLine
% ***
% *** Returns the code for drawing a regular line.
% *** This is an extremely common operation and takes place in most of the
% *** not too fancy plots.
% ***
% *** This function handles error bars, too.
% ***
% =========================================================================
function str = drawLine( handle, yDeviation )
global currentHandles
% TODO Check for "special" lines, e.g.:
% if strcmp( get(handle,'Tag'), 'zplane_unitcircle' )
% % draw unit circle and axes
% end
% check if the *optional* argument 'yDeviation' was given
errorbarMode = 0;
if nargin>1
errorbarMode = 1;
end
str = [];
if ~isVisible( handle )
return
end
lineStyle = get( handle, 'LineStyle' );
lineWidth = get( handle, 'LineWidth' );
marker = get( handle, 'Marker' );
if ( strcmp(lineStyle,'none') || lineWidth==0 ) && strcmp(marker,'none')
return
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% deal with draw options
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
color = get( handle, 'Color' );
xcolor = getColor( handle, color, 'patch' );
drawOptions = [ sprintf( 'color=%s', xcolor ), ... % color
getLineOptions( lineStyle, lineWidth ), ... % line options
getMarkerOptions( handle ) ... % marker options
];
% insert draw options
opts = [ '\n', collapse( drawOptions, ',\n' ), '\n' ];
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% plot the actual line data
% -- Check for any node if it needs to be included at all. For zoomed
% plots, lots can be omitted.
p = currentHandles.gca;
xLim = get( p, 'XLim' );
yLim = get( p, 'YLim' );
xData = get( handle, 'XData' );
yData = get( handle, 'YData' );
% split the data into logical chunks
if errorbarMode
[xDataCell, yDataCell, yDeviationCell ] = splitLine( xData, yData, xLim, yLim, yDeviation );
else
[xDataCell, yDataCell] = splitLine( xData, yData, xLim, yLim );
end
% plot them
for k = 1:length(xDataCell)
mask = pointReduction( xDataCell{k}, yDataCell{k} );
if errorbarMode
plotLine( xDataCell{k}(mask), yDataCell{k}(mask), yDeviationCell{k}(mask) );
else
plotLine( xDataCell{k}(mask), yDataCell{k}(mask) );
end
end
str = [ str, handleAllChildren( handle ) ];
% -----------------------------------------------------------------------
% FUNCTION plotLine
% -----------------------------------------------------------------------
function plotLine( xData, yData, yDeviation )
% check if the *optional* argument 'yDeviation' was given
errorbarMode = 0;
if nargin>2
errorbarMode = 1;
end
n = length(xData);
if errorbarMode
if n~=length(yDeviation)
error( 'drawLine:arrayLengthsMismatch', ...
'''drawline'' was called with errors bars turned on, but array lengths do not match.' );
end
end
str = [ str, ...
sprintf( ['\\addplot [',opts,']\n'] ) ];
if errorbarMode
str = [ str, ...
sprintf('plot[error bars/.cd, y dir = both, y explicit]\n') ];
end
str = [ str, ...
sprintf('coordinates{\n') ];
for l = 1:length(xData)
str = [ str, ...
sprintf( ' (%g,%g)\n', xData(l), yData(l) ) ];
if errorbarMode
str = [ str, ...
sprintf( ' +- (%g,%g)\n', 0.0, yDeviation(l) ) ];
end
end
str = [ str, sprintf('\n};\n\n') ];
end
% -----------------------------------------------------------------------
% END FUNCTION plotLine
% -----------------------------------------------------------------------
% -----------------------------------------------------------------------
% FUNCTION splitLine
%
% Split the xData, yData into several chunks of data for each of which
% an \addplot will be generated.
% Splitting criteria are:
% * NaNs.
% If xData or yData contain a NaN at position K, the data gets
% split up into index groups [1:k-1],[k+1:end].
% * Visibility.
% Parts of the line data may sit outside the plotbox.
% 'segvis' tells us which segment are actually visible, and the
% following construction loops through it and makes sure that each
% point that is necessary gets actually printed.
% 'printPrevious' tells whether or not the previous segment is visible;
% this information is used for determining when a new 'addplot' needs
% to be opened.
% * Dimension too large.
% Connected points may sit outside the plot, but their connecting
% line may not. The values of the outside plot may be too large for
% LaTeX to handle. Move those points closer to the bounding box,
% and possibly split them up in two.
%
% -----------------------------------------------------------------------
function [xDataCell, yDataCell, yDeviationCell] = splitLine( xData, yData, xLim, yLim, yDeviation )
% check if the *optional* argument 'yDeviation' was given
errorbarMode = 0;
if nargin>4
errorbarMode = 1;
end
xDataCell{1} = xData;
yDataCell{1} = yData;
if errorbarMode
yDeviationCell{1} = yDeviation;
end
% Split up at Infs and NaNs.
mask = splitByInfsNaNs( xDataCell, yDataCell );
xDataCell = splitByMask( xDataCell, mask );
yDataCell = splitByMask( yDataCell, mask );