This repository was archived by the owner on Aug 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatlab2tikz.m
executable file
·5017 lines (4442 loc) · 197 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( varargin )
%MATLAB2TIKZ Save figure in native LaTeX (TikZ/Pgfplots).
% MATLAB2TIKZ() saves the current figure as LaTeX file.
% MATLAB2TIKZ comes with several options that can be combined at will.
%
% MATLAB2TIKZ(FILENAME,...) or MATLAB2TIKZ('filename',FILENAME,...)
% stores the LaTeX code in FILENAME.
%
% MATLAB2TIKZ('filehandle',FILEHANDLE,...) stores the LaTeX code in the file
% referenced by FILEHANDLE. (default: [])
%
% MATLAB2TIKZ('figurehandle',FIGUREHANDLE,...) explicitly specifies the
% handle of the figure that is to be stored. (default: gcf)
%
% MATLAB2TIKZ('colormap',DOUBLE,...) explicitly specifies the colormap to be
% used. (default: current color map)
%
% MATLAB2TIKZ('strict',BOOL,...) tells MATLAB2TIKZ to adhere to MATLAB(R)
% conventions wherever there is room for relaxation. (default: FALSE)
%
% MATLAB2TIKZ('showInfo',BOOL,...) turns informational output on or off.
% (default: true)
%
% MATLAB2TIKZ('showWarning',BOOL,...) turns warnings on or off.
% (default: true)
%
% MATLAB2TIKZ('imagesAsPng',BOOL,...) stores MATLAB(R) images as (lossless)
% PNG files. This is more efficient than storing the image color data as TikZ
% matrix. (default: true)
%
% MATLAB2TIKZ('relativePngPath',CHAR, ...) tells MATLAB2TIKZ to use the given
% path to follow the PNG file. If LaTeX source and PNG file will reside in
% the same directory, this can be set to '.'. (default: [])
%
% MATLAB2TIKZ('height',CHAR,...) sets the height of the image. This can be any
% LaTeX-compatible length, e.g., '3in' or '5cm' or '0.5\textwidth'.
% If unspecified, MATLAB2TIKZ tries to make a reasonable guess.
%
% MATLAB2TIKZ('width',CHAR,...) sets the width of the image.
% If unspecified, MATLAB2TIKZ tries to make a reasonable guess.
%
% MATLAB2TIKZ('minimumPointsDistance',DOUBLE,...) gives a minimum distance at
% which two nodes are considered different. This can help with plots that
% contain a large amount of data points not all of which need to be plotted.
% (default: 0.0)
%
% MATLAB2TIKZ('extraAxisOptions',CHAR or CELLCHAR,...) explicitly adds extra
% options to the Pgfplots axis environment. (default: [])
%
% MATLAB2TIKZ('extraTikzpictureSettings',CHAR or CELLCHAR,...)
% explicitly adds extra settings to the tikzpicture environment. (default: [])
%
% MATLAB2TIKZ('encoding',CHAR,...) sets the encoding of the output file.
%
% MATLAB2TIKZ('parseStrings',BOOL,...) determines whether title, axes labels
% and the like are parsed into LaTeX by MATLAB2TIKZ's parser.
% If you want greater flexibility, set this to false and use straight LaTeX
% for your labels. (default: true)
%
% MATLAB2TIKZ('parseStringsAsMath',BOOL,...) determines whether to use TeX's
% math mode for more characters (such as operators and figures).
% (default: false)
%
% MATLAB2TIKZ('interpretTickLabelsAsTex',BOOL,...) determines whether to
% interpret tick labels as TeX. MATLAB(R) doesn't do that by default.
% (default: false)
%
% MATLAB2TIKZ('tikzFileComment',CHAR,...) adds a custom comment to the header
% of the output file.
%
% Example
% x = -pi:pi/10:pi;
% y = tan(sin(x)) - sin(tan(x));
% plot(x,y,'--rs');
% matlab2tikz( 'myfile.tex' );
%
% See also PRINT.
% Copyright (c) 2008--2012, 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.
% *** -------
% *** 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: * Replace slow strcat() in loops with Julien Ridoux' idea.
% *** (See function plotLine().)
% ***
% =========================================================================
% Check if we are in MATLAB or Octave.
m2t.env = getEnvironment();
warningMessage = [ '\n',...
'================================================================================\n\n', ...
' matlab2tikz is tested and developed on %s and\n', ...
' later versions of %s.\n', ...
' This script may still be able to handle your plots, but if you\n', ...
' hit a bug, please consider upgrading your environment first.\n', ...
'\n', ...
' Every time you submit a bug report with a deprecated environment...\n', ...
' God kills a kitten.\n', ...
'\n', ...
'================================================================================' ];
switch m2t.env
case 'MATLAB'
% Make sure we're running MATLAB >= 2008b.
if isVersionBelow( m2t.env, 7, 7)
warning( warningMessage, 'MATLAB 2008b', 'MATLAB' );
end
case 'Octave'
% Make sure we're running Octave >= 3.4.0.
if isVersionBelow( m2t.env, 3, 4)
warning( warningMessage, 'Octave 3.4.0', 'Octave' );
end
otherwise
error( 'Unknown environment. Need MATLAB(R) or Octave.' )
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
m2t.cmdOpts = [];
m2t.currentHandles = [];
m2t.name = 'matlab2tikz';
m2t.version = '0.2.0';
m2t.author = 'Nico Schlömer';
m2t.authorEmail = '[email protected]';
m2t.years = '2008--2012';
m2t.website = 'http://www.mathworks.com/matlabcentral/fileexchange/22022-matlab2tikz';
m2t.tikzOptions = cell(0); % for the arrow style -- TODO: see if we can get this removed
m2t.tol = 1.0e-15; % global round-off tolerance;
% used, for example, in equality test for doubles
m2t.relativePngPath = [];
% The following color RBG-values which will need to be defined.
% 'extraRgbColorNames' contains their designated names, 'extraRgbColorSpecs'
% their specifications.
m2t.extraRgbColorSpecs = cell(0);
m2t.extraRgbColorNames = cell(0);
% the actual contents of the TikZ file go here
m2t.content = struct( 'name', [], ...
'comment', [], ...
'options', [], ...
'content', [], ...
'children', [] ...
);
% Setting the following to cell(0) straight away doesn't work unfortunately
% as MATLAB(R) interprets structs with cell values as a cell array of structs.
m2t.content.options = cell(0);
m2t.content.content = cell(0);
m2t.content.children = cell(0);
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% scan the options
m2t.cmdOpts = matlab2tikzInputParser;
m2t.cmdOpts = m2t.cmdOpts.addOptional( m2t.cmdOpts, ...
'filename', ...
[], ...
@(x) filenameValidation(x,m2t.cmdOpts) );
% possibility to give a file handle as argument
m2t.cmdOpts = m2t.cmdOpts.addOptional( m2t.cmdOpts, 'filehandle', [], @filehandleValidation );
% explicitly specify which figure to use
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'figurehandle', gcf, @ishandle );
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'colormap', colormap, @isnumeric );
% whether to strictly stick to the default MATLAB plot appearance:
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'strict', false, @islogical );
% deprecated parameter -- keep it to allow warning further down
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'silent', false, @islogical );
% don't print warning messages
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'showInfo', true, @islogical );
% don't print informational messages
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'showWarnings', true, @islogical );
% Whether to save images in PNG format or to natively draw filled squares
% using TikZ itself.
% Default it PNG.
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'imagesAsPng', true, @islogical );
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'relativePngPath', [], @ischar );
% width and height of the figure
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'height', [], @ischar );
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'width' , [], @ischar );
% minimum distance for two points to be plotted separately
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'minimumPointsDistance', 0.0, @isnumeric );
% extra axis options
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'extraAxisOptions', {}, @isCellOrChar );
% extra tikzpicture settings
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'extraTikzpictureSettings', {}, @isCellOrChar );
% file encoding
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'encoding' , '', @ischar );
% deprecated parameter -- keep it to allow warning further down
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'mathmode', true, @islogical );
% By default strings like axis labels are parsed to match the appearance of
% strings as closely as possible to that generated by MATLAB.
% If the user wants to have particular strings in the matlab2tikz output that
% can't be generated in MATLAB, they can disable string parsing. In that case
% all strings are piped literally to the LaTeX output.
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'parseStrings', true, @islogical );
% In addition to regular string parsing, an additional stage can be enabled
% which uses TeX's math mode for more characters like figures and operators.
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'parseStringsAsMath', false, @islogical );
% As opposed to titles, axis labels and such, MATLAB(R) does not interpret tick
% labels as TeX. matlab2tikz retains this behavior, but if it is desired to
% interpret the tick labels as TeX, set this option to true.
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'interpretTickLabelsAsTex', false, @islogical );
% Allow a string to be added to the header of the generated TikZ file.
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'tikzFileComment', '', @ischar );
m2t.cmdOpts = m2t.cmdOpts.parse( m2t.cmdOpts, varargin{:} );
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% warn for deprecated options
if any( ismember( m2t.cmdOpts.Parameters, 'silent' ) )
warning( sprintf( [ '\n===============================================================================\n', ...
'You are using the deprecated parameter ''silent''.\n', ...
'From now on, please use ''showInfo'' and ''showWarnings'' to control the output.\n', ...
'===============================================================================' ] ) );
end
if any( ismember( m2t.cmdOpts.Parameters, 'mathmode' ) )
warning( sprintf( [ '\n===============================================================================\n', ...
'You are using the deprecated parameter ''mathmode''.\n', ...
'From now on, please use ''parseStrings'' and ''parseStringsAsMath'' to control\n', ...
'the output.\n', ...
'===============================================================================' ] ) );
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% inform users of potentially dangerous options
if m2t.cmdOpts.Results.parseStringsAsMath
userInfo( m2t, [ '\n==========================================================================\n', ...
'You are using the parameter ''parseStringsAsMath''.\n', ...
'This may produce undesirable string output. For full control over output\n', ...
'strings please set the parameter ''parseStrings'' to false.\n', ...
'==========================================================================' ] );
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% add global elements
m2t.currentHandles.gcf = m2t.cmdOpts.Results.figurehandle;
m2t.currentHandles.colormap = get(m2t.currentHandles.gcf,'colormap');
% TODO: Shouldn't this use m2t.cmdOpts.Results.colormap, if specified?
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% handle output file handle/file name
if ~isempty( m2t.cmdOpts.Results.filehandle )
fid = m2t.cmdOpts.Results.filehandle;
fileWasOpen = 1;
if ~isempty(m2t.cmdOpts.Results.filename)
userWarning( m2t, ...
'File handle AND file name for output given. File handle used, file name discarded.')
end
else
fileWasOpen = 0;
% set filename
if ~isempty(m2t.cmdOpts.Results.filename)
filename = m2t.cmdOpts.Results.filename;
else
filename = uiputfile( {'*.tikz'; '*.*'}, ...
'Save File' );
end
% open the file for writing
if strcmp( m2t.env, 'MATLAB' );
fid = fopen( filename, ...
'w', ...
'native', ...
m2t.cmdOpts.Results.encoding ...
);
elseif strcmp( m2t.env, 'Octave' );
fid = fopen( filename, 'w' );
else
error( 'Unknown environment. Need MATLAB(R) or Octave.' )
end
if fid == -1
error( 'matlab2tikz:fileOpenError', ...
'Unable to open file ''%s'' for writing.', ...
filename );
end
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
m2t.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(m2t.cmdOpts.Results.relativePngPath)
m2t.relativePngPath = fileparts(m2t.tikzFileName);
else
m2t.relativePngPath = m2t.cmdOpts.Results.relativePngPath;
end
% print some version info to the screen
userInfo( m2t, [ '\nThis is %s v%s.\n' , ...
'The latest updates can be retrieved from\n\n', ...
' %s\n\n', ...
'where you can also make suggestions and rate %s.\n' ], ...
m2t.name, m2t.version, m2t.website, m2t.name );
userInfo( m2t, [ 'matlab2tikz uses features of Pgfplots which may only be available in recent versions.\n', ...
'Make sure you have at least Pgfplots 1.3 available.\n', ...
'For best results, use \\pgfplotsset{compat=newest},\n', ...
'and for speed ', ...
'use \\pgfplotsset{plot coordinates/math parser=false} .\n' ] );
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Save the figure as pgf to file -- here's where the work happens
saveToFile( m2t, fid, fileWasOpen );
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
userInfo( m2t, '\nRemember to load \\usepackage{pgfplots} in the preamble of your LaTeX document.\n' );
end
% =========================================================================
% validates the optional argument 'filename' to not be 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
% =========================================================================
function m2t = saveToFile( m2t, fid, fileWasOpen )
% Save the figure as TikZ to a file.
% All other routines are called from here.
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% 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 = m2t.currentHandles.gcf;
axesHandles = findobj( fh, 'type', 'axes' );
% remove all legend handles as they are treated separately
rmList = [];
m2t.legendHandles = [];
for k = 1:length(axesHandles)
if strcmp( get(axesHandles(k),'Tag'), 'legend' )
m2t.legendHandles = [m2t.legendHandles, axesHandles(k)];
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( m2t, axesHandles );
for k = 1:length(visibleAxesHandles)
m2t = drawAxes( m2t, visibleAxesHandles(ix(k)), alignmentOptions(ix(k)) );
m2t.content = addChildren( m2t.content, m2t.currentAxesContainer );
end
set( 0, 'ShowHiddenHandles', 'off' );
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% actually print the stuff
m2t.content.comment = sprintf( [ 'This file was created by %s v%s.\n', ...
'Copyright (c) %s, %s <%s>\n', ...
'All rights reserved.\n' ], ...
m2t.name, m2t.version, ...
m2t.years, m2t.author, m2t.authorEmail );
if ~m2t.cmdOpts.Results.silent && m2t.cmdOpts.Results.showInfo
% disable this info if silent=true or showInfo=false
m2t.content.comment = [ m2t.content.comment, ...
sprintf( [ '\n',...
'The latest updates can be retrieved from\n', ...
' %s\n', ...
'where you can also make suggestions and rate %s.\n' ], ...
m2t.website, m2t.name ) ...
];
end
% Add custom comment.
m2t.content.comment = [ m2t.content.comment, ...
sprintf( '\n%s\n', m2t.cmdOpts.Results.tikzFileComment )
];
m2t.content.name = 'tikzpicture';
m2t.content.options = { m2t.content.options{:}, m2t.tikzOptions{:} };
% Add custom TikZ options if any given.
if ~isempty( m2t.cmdOpts.Results.extraTikzpictureSettings )
if ischar(m2t.cmdOpts.Results.extraTikzpictureSettings)
m2t.cmdOpts.Results.extraTikzpictureSettings = ...
{m2t.cmdOpts.Results.extraTikzpictureSettings};
end
for k = 1:length(m2t.cmdOpts.Results.extraTikzpictureSettings)
m2t.content = append( m2t.content, ...
sprintf('%s\n', m2t.cmdOpts.Results.extraTikzpictureSettings{k}) ...
);
end
end
% Don't forget to define the colors.
if ~isempty(m2t.extraRgbColorNames)
m2t.content = append( m2t.content, ...
sprintf('\n%% defining custom colors\n') ...
);
for k = 1:length(m2t.extraRgbColorNames)
m2t.content = append( m2t.content, ...
sprintf('\\definecolor{%s}{rgb}{%.15g,%.15g,%.15g}\n', ...
m2t.extraRgbColorNames{k}, m2t.extraRgbColorSpecs{k}) ...
);
end
m2t.content = append( m2t.content, sprintf('\n') );
end
% finally print it to the file
printAll( m2t.content, fid );
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% close the file if necessary
if ~fileWasOpen
fclose( fid );
end
end
% =========================================================================
function [ m2t, pgfEnvironments ] = handleAllChildren( m2t, handle )
% Draw all children of a graphics object (if they need to be drawn).
% prepare cell array of pgfEnvironments
pgfEnvironments = cell(0);
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' )
% 'axes' environments are treated separately.
case 'line'
[m2t, env] = drawLine( m2t, child );
case 'patch'
[m2t, env] = drawPatch( m2t, child );
case 'image'
[m2t, env] = drawImage( m2t, child );
case 'hggroup'
[m2t, env] = drawHggroup( m2t, child );
case 'hgtransform'
% don't handle those directly but descend to its children
% (which could for example be patch handles)
[m2t, env] = handleAllChildren( m2t, child );
case 'surface'
[m2t, env] = drawSurface( m2t, child );
case 'text'
[m2t, env] = drawText( m2t, child );
case 'rectangle'
[m2t, env] = drawRectangle( m2t, child );
case { 'uitoolbar', 'uimenu', 'uicontextmenu', 'uitoggletool',...
'uitogglesplittool', 'uipushtool', 'hgjavacomponent'}
% don't to anything for these handles and its children
env = [];
otherwise
error( 'matlab2tikz:handleAllChildren', ...
'I don''t know how to handle this object: %s\n', ...
get(child,'Type') );
end
% append the environment
pgfEnvironments = [ pgfEnvironments, {env} ];
end
end
% =========================================================================
function m2t = drawAxes( m2t, handle, alignmentOptions )
% Input arguments:
% handle.................The axes environment handle.
% alignmentOptions.......The alignment options as defined in the
% function `alignSubPlots()`.
% This argument is optional.
% Initialize empty enviroment.
% Use a struct instead of a custom subclass of hgsetget (which would
% facilitate writing clean code) as structs are more portable (old MATLAB(R)
% versions, GNU Octave).
m2t.currentAxesContainer = struct( 'name', [], ...
'comment', [], ...
'options', [], ...
'content', [], ...
'children', [] ...
);
% Setting the following to cell(0) straight away doesn't work unfortunately
% as MATLAB(R) interprets structs with cell values as a cell array of structs.
m2t.currentAxesContainer.options = cell(0);
m2t.currentAxesContainer.content = cell(0);
m2t.currentAxesContainer.children = cell(0);
% Handle special cases.
% MATLAB(R) uses 'Tag', Octave 'tag' for their tags. :/
if strcmp( m2t.env, 'MATLAB' );
tagKeyword = 'Tag';
colorbarKeyword = 'Colorbar';
elseif strcmp( m2t.env, 'Octave' );
tagKeyword = 'tag';
colorbarKeyword = 'colorbar';
else
error( 'Unknown environment. Need MATLAB(R) or GNU Octave.' )
end
switch get( handle, tagKeyword )
case colorbarKeyword
% Handle a colorbar separately.
% Note that m2t.currentHandles.gca does *not* get updated.
% Within drawColorbar(), m2t.currentHandles.gca is assumed to point
% to the parent axes.
[m2t, m2t.currentAxesContainer] = drawColorbar( m2t, handle, alignmentOptions );
return
case 'legend'
% Don't handle the legend here, but further below in the 'axis'
% environment.
% In MATLAB, an axes environment and its 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
m2t.currentHandles.gca = handle;
% get the view angle
view = get( handle, 'View' );
m2t.is3dPlot = false;
if any( view ~= [0,90] )
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
sprintf( 'view={%.15g}{%.15g}', get( handle, 'View') ) ...
};
m2t.is3dPlot = true;
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get the axes dimensions
dim = getAxesDimensions( handle, ...
m2t.cmdOpts.Results.width, ...
m2t.cmdOpts.Results.height );
% set the width
if dim.x.unit(1)=='\' && dim.x.value==1.0
% only return \figurewidth instead of 1.0\figurewidth
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:},...
sprintf('width=%s', dim.x.unit)};
else
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:},...
sprintf('width=%.15g%s', dim.x.value, dim.x.unit)};
end
if dim.y.unit(1)=='\' && dim.y.value==1.0
% only return \figureheight instead of 1.0\figureheight
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
sprintf('height=%s', dim.y.unit)};
else
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:},...
sprintf('height=%.15g%s', dim.y.value, dim.y.unit)};
end
% Add the physical dimension of one unit of length in the coordinate system.
% This is used later on to translate lenghts to physical units where
% necessary (e.g., in bar plots).
m2t.unitlength.x.unit = dim.x.unit;
xLim = get( m2t.currentHandles.gca, 'XLim' );
m2t.unitlength.x.value = dim.x.value / (xLim(2)-xLim(1));
m2t.unitlength.y.unit = dim.y.unit;
yLim = get( m2t.currentHandles.gca, 'YLim' );
m2t.unitlength.y.value = dim.y.value / (yLim(2)-yLim(1));
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% the following is general MATLAB behavior
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
'scale only axis'};
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Get other axis options (ticks, axis color, label,...).
% This is set here such that the axis orientation indicator in m2t is set
% before -- if ~isVisible(handle) -- the handle's children are called.
[ m2t, hasXGrid ] = getAxisOptions( m2t, handle, 'x' );
[ m2t, hasYGrid ] = getAxisOptions( m2t, handle, 'y' );
if m2t.is3dPlot
[ m2t, hasZGrid ] = getAxisOptions( m2t, handle, 'z' );
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if ~isVisible( handle )
% An invisible axes container *can* have visible children, so don't
% immediately bail out here.
c = get(handle,'Children');
for k = 1:length(c)
if isVisible( c(k) )
% If the axes contain something that's visible, add an invisible
% axes pair.
m2t.currentAxesContainer.name = 'axis';
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
'hide x axis', 'hide y axis'};
m2t.currentAxesContainer.comment = getTag( handle );
break;
end
end
% recurse into the children of this environment
[ m2t, childrenEnvs ] = handleAllChildren( m2t, handle );
m2t.currentAxesContainer = addChildren( m2t.currentAxesContainer, childrenEnvs );
return
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if strcmp( get( handle, 'Box' ), 'off' )
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:},...
'axis lines=left'};
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get scales
isXLog = strcmp( get( handle, 'XScale' ), 'log' );
isYLog = strcmp( get( handle, 'YScale' ), 'log' );
if m2t.is3dPlot
m2t.currentAxesContainer.name = 'axis';
elseif ~isXLog && ~isYLog
m2t.currentAxesContainer.name = 'axis';
elseif isXLog && ~isYLog
m2t.currentAxesContainer.name = 'semilogxaxis';
elseif ~isXLog && isYLog
m2t.currentAxesContainer.name = 'semilogyaxis';
else
m2t.currentAxesContainer.name = 'loglogaxis';
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% set alignment options
if ~isempty(alignmentOptions.opts)
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:},...
alignmentOptions.opts{:}};
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% background color
backgroundColor = get( handle, 'Color' );
if ~strcmp( backgroundColor, 'none' )
[ m2t, col ] = getColor( m2t, handle, backgroundColor, 'patch' );
if ~strcmp( col, 'white' )
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
sprintf( 'axis background/.style={fill=%s}', col)};
end
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% title
title = get( get( handle, 'Title' ), 'String' );
if ~isempty(title)
titleText = sprintf( '%s', title );
titleInterpreter = get( get( handle, 'Title' ), 'Interpreter' );
titleText = prettyPrint( m2t, titleText, titleInterpreter );
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
sprintf( 'title={%s}', titleText)};
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% For double axes pairs, unconditionally put the ordinate left for the
% first one, right for the second one.
if alignmentOptions.isElderTwin
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
'axis y line*=left', 'axis x line*=bottom'};
elseif alignmentOptions.isYoungerTwin
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
'axis y line*=right', 'axis x line*=top'};
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% add manually given extra axis options
if ~isempty( m2t.cmdOpts.Results.extraAxisOptions )
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
m2t.cmdOpts.Results.extraAxisOptions{:}};
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% grid line style
if hasXGrid || hasYGrid || (exist('hasZGrid','var') && hasZGrid )
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 m2t.cmdOpts.Results.strict ...
|| ~strcmp(matlabGridLineStyle,defaultMatlabGridLineStyle)
gls = translateLineStyle( matlabGridLineStyle );
axisGridOpts = sprintf( 'grid style={%s}', gls );
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:},...
axisGridOpts{:}};
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.
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:},...
'axis on top'};
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% See if there are any legends that need to be plotted.
% 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.
if strcmp( m2t.env, 'MATLAB' )
legendHandle = legend(handle);
if ~isempty(legendHandle)
[ m2t, legendOpts ] = getLegendOpts( m2t, legendHandle );
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, legendOpts{:}};
end
else
% TODO: How to uniquely connect a legend with a pair of axes in Octave?
axisDims = get(handle,'Position');
axisLeft = axisDims(1);
axisBot = axisDims(2);
axisWid = axisDims(3);
axisHei = axisDims(4);
% siblings of this handle:
siblings = get( get(handle,'Parent'), 'Children' );
% "siblings" always(?) is a column vector. Iterating over the column
% with the for statement below wouldn't return the individual vector
% elements but the same column vector, resulting in no legends exported.
% So let's make sure "siblings" is a row vector by reshaping it:
siblings = reshape( siblings, 1, [] );
for sibling = siblings
if sibling && strcmp(get(sibling,'Type'), 'axes') && strcmp(get(sibling,'Tag' ), 'legend')
legDims = get( sibling, 'Position' );
legLeft = legDims(1);
legBot = legDims(2);
legWid = legDims(3);
legHei = legDims(4);
% TODO The following logic does not work for 3D plots.
% => Commented out.
% This creates problems though for stacked plots with legends.
% if ( legLeft > axisLeft ...
% && legBot > axisBot ...
% && legLeft+legWid < axisLeft+axisWid ...
% && legBot+legHei < axisBot+axisHei )
[ m2t, legendOpts ] = getLegendOpts( m2t, sibling );
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, legendOpts{:}};
% end
end
end
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% recurse into the children of this environment
[ m2t, childrenEnvs ] = handleAllChildren( m2t, handle );
m2t.currentAxesContainer = addChildren( m2t.currentAxesContainer, childrenEnvs );
return
end
% =========================================================================
function tag = getTag( handle )
% if a tag is given, use it as comment
tag = get(handle, 'tag');
if ~isempty(tag)
tag = sprintf( 'Axis "%s"', tag );
else
tag = sprintf( 'Axis at [%.2g %.2f %.2g %.2g]', get(handle, 'position' ) );
end
end
% =========================================================================
function [ m2t, hasGrid ] = getAxisOptions( m2t, handle, axis )
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if ~strcmpi(axis,'x') && ~strcmpi(axis,'y') && ~strcmpi(axis,'z')
error( 'Illegal axis specifier ''%s''.', axis );
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% axis colors
color = get( handle, [upper(axis),'Color'] );
if ( any(color) ) % color not black [0,0,0]
[ m2t, col ] = getColor( m2t, handle, color, 'patch' );
m2t.currentAxesContainer.options = ...
{m2t.currentAxesContainer.options{:}, ...
['every outer ',axis,' axis line/.append style={',col, '}'], ...
['every ',axis,' tick label/.append style={font=\color{',col,'}}' ]};
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% handle the orientation
isAxisReversed = strcmp( get(handle,[upper(axis),'Dir']), 'reverse' );
m2t = setfield( m2t, [axis,'AxisReversed'], isAxisReversed );
if isAxisReversed
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
[axis,' dir=reverse']};
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get axis limits
limits = get( handle, [upper(axis),'Lim'] );
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
sprintf( [axis,'min=%.15g, ',axis,'max=%.15g'], limits)};
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get ticks along with the labels
[ticks, tickLabels, hasMinorTicks] = getIndividualAxisTicks( m2t, handle, axis );
% According to http://www.mathworks.com/help/techdoc/ref/axes_props.html,
% the number of minor ticks is automatically determined by MATLAB(R) to
% fit the size of the axis. Until we know how to extract this number, use
% a reasonable default.
matlabDefaultNumMinorTicks = 3;
if ~isempty( ticks )
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:},...
sprintf( [axis,'tick={%s}'], ticks )};
end
if ~isempty( tickLabels )
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
sprintf([axis,'ticklabels={%s}'], tickLabels)};
end
if hasMinorTicks
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
[axis,'minorticks=true']};
if m2t.cmdOpts.Results.strict
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
sprintf('minor %s tick num={%d}', axis, matlabDefaultNumMinorTicks)};
end
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get axis label
axisLabel = get( get( handle, [upper(axis),'Label'] ), 'String' );
if iscell(axisLabel)
axisLabel = axisLabel{:};
end
if ~isempty( axisLabel )
labelText = sprintf( '%s', axisLabel );
axisLabelInterpreter = get( get( handle, [upper(axis),'Label'] ), 'Interpreter' );
labelText = prettyPrint( m2t, labelText, axisLabelInterpreter );
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
sprintf([axis,'label={%s}'], labelText)};
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get grids
hasGrid = false;
if strcmp( get( handle, [upper(axis),'Grid']), 'on' );
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
[axis,'majorgrids']};
hasGrid = true;
end
if strcmp( get( handle, [upper(axis),'MinorGrid']), 'on' );
m2t.currentAxesContainer.options = {m2t.currentAxesContainer.options{:}, ...
[axis,'minorgrids']};
hasGrid = true;
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
return;
end
% =========================================================================
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
% =========================================================================
function [ m2t, str ] = drawLine( m2t, handle, yDeviation )
% 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.
% 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>2
errorbarMode = true;
end
str = [];
if ~isVisible( handle )
return
end
lineStyle = get( handle, 'LineStyle' );
lineWidth = get( handle, 'LineWidth' );
marker = get( handle, 'Marker' );
hasLines = ~strcmp(lineStyle,'none') & lineWidth>0.0;
hasMarkers = ~strcmp(marker,'none');
if ~hasLines && ~hasMarkers
return
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% deal with draw options
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
color = get( handle, 'Color' );
[ m2t, xcolor ] = getColor( m2t, handle, color, 'patch' );
lineOptions = getLineOptions( m2t, lineStyle, lineWidth );
[ m2t, markerOptions ] = getMarkerOptions( m2t, handle );
drawOptions = [ {sprintf( 'color=%s', xcolor )}, ... % color
lineOptions, ...
markerOptions ];
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Conditional \addlegendentry.
legendString = [];
if ~isempty(m2t.legendHandles)
% Check if current handle is referenced in a legend.
ud = get(m2t.legendHandles(1), 'UserData');
k = find(handle == ud.handles);
if isempty(k)
% Lines of error bar plots are not referenced directly in legends
% as an error bars plot contains two "lines": the data and the
% deviations. Here, the legends refer to the specgraph.errorbarseries
% handle which is 'Parent' to the line handle.
k = find(get(handle,'Parent') == ud.handles);
end
if ~isempty(k)
% Legend entry found. Add it to the plot.
switch m2t.env