Git Product home page Git Product logo

matlab2tikz / matlab2tikz Goto Github PK

View Code? Open in Web Editor NEW
1.5K 87.0 318.0 7.57 MB

This program converts MATLAB®/Octave figures to TikZ/pgfplots figures for smooth integration into LaTeX.

Home Page: http://www.mathworks.com/matlabcentral/fileexchange/22022-matlab2tikz

License: BSD 2-Clause "Simplified" License

Makefile 0.21% MATLAB 99.37% Shell 0.42%
matlab tikz pgfplots octave matlab2tikz latex

matlab2tikz's Introduction

The updater in matlab2tikz 0.6.0 (and older) no longer works. Please update manually if you are not using matlab2tikz 1.0.0 or newer!

Build Status DOI matlab2tikz

matlab2tikz is a MATLAB(R) script to convert native MATLAB(R) figures to TikZ/Pgfplots figures that integrate seamlessly in LaTeX documents.

To download the official releases and rate matlab2tikz, please visit its page on FileExchange.

matlab2tikz converts most MATLAB(R) figures, including 2D and 3D plots. For plots constructed with third-party packages, however, your mileage may vary.

Installation

  1. Extract the ZIP file (or clone the git repository) somewhere you can easily reach it.
  2. Add the src/ folder to your path in MATLAB/Octave: e.g.
    • using the "Set Path" dialog in MATLAB, or
    • by running the addpath function from your command window or startup script.

Make sure that your LaTeX installation is up-to-date and includes:

It is recommended to use the latest stable version of these packages. Older versions may work depending on the actual MATLAB(R) figure you are converting.

Usage

Typical usage of matlab2tikz consists of converting your MATLAB plot to a TikZ/LaTeX file and then running a LaTeX compiler to produce your document.

MATLAB

  1. Generate your plot in MATLAB(R).

  2. Run matlab2tikz, e.g. using

matlab2tikz('myfile.tex');

LaTeX

Add the contents of myfile.tex into your LaTeX source code, for example using \input{myfile.tex}. Make sure that the required packages (such as pgfplots) are loaded in the preamble of your document as in the example:

\documentclass{article}

  \usepackage{pgfplots}
  \pgfplotsset{compat=newest}
  %% the following commands are needed for some matlab2tikz features
  \usetikzlibrary{plotmarks}
  \usetikzlibrary{arrows.meta}
  \usepgfplotslibrary{patchplots}
  \usepackage{grffile}
  \usepackage{amsmath}

  %% you may also want the following commands
  %\pgfplotsset{plot coordinates/math parser=false}
  %\newlength\figureheight
  %\newlength\figurewidth

\begin{document}
  \input{myfile.tex}
\end{document}

Remarks

Most functions accept numerous options; you can check them out by inspecting their help:

help matlab2tikz

Sometimes, MATLAB(R) plots contain some features that impede conversion to LaTeX; e.g. points that are far outside of the actual bounding box. You can invoke the cleanfigure function to remove such unwanted entities before calling matlab2tikz:

cleanfigure;
matlab2tikz('myfile.tex');

More information

  • For more information about matlab2tikz, have a look at our GitHub repository. If you are a good MATLAB(R) programmer or LaTeX writer, you are always welcome to help improving matlab2tikz!
  • Some common problems and pit-falls are documented in our wiki.
  • If you experience (other) bugs or would like to request a feature, please visit our issue tracker.

matlab2tikz's People

Contributors

aikhjarto avatar akloeckner avatar blubbafett avatar broele avatar corrmaan avatar dehorsley avatar egeerardyn avatar egocentrix avatar jam4375 avatar job89 avatar josombio avatar jtsvejda avatar ljeub avatar m-pilia avatar magicmuscleman avatar miscco avatar murmlgrmpf avatar nschloe avatar patrickkwang avatar peterpablo avatar raimund-schluessler avatar rmcdermo avatar rpeschke avatar schiller-manuel avatar sil2100 avatar svillemot avatar tgroche avatar theswitch avatar tomlankhorst avatar ulijh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

matlab2tikz's Issues

Writing to pgfAxis environment from other function than drawAxes()

In drawAxes() this is written:

% Store a pointer to the current pgfplotsEnvironment axis environment
% 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.
m2t.currentHandles.pgfAxis = env;

which makes me believe that I can update the content (m2t.currentHandles.pgfAxis.options) from another nested function before the content is printed to the actual file.

Thus, if I in f.ex drawLine() want to append something, I could write:

pgfAxis = m2t.currentHandles.pgfAxis.options;
newOpts = blablabla;
pgfAxis = appendOptions( pgfAxis, newOpts );
m2t.currentHandles.pgfAxis.options = pgfAxis;

But after trying for a while now it's obvious I'm missing out on something; the options are indeed updated in the struct, but not printed to the file.

So the question is; what am I missing here?

cell strings of labels

In many of my plots the labels seems to be stored as cell of strings in the figure. That is why sprintf breaks in matlab2tikz when writing the labels. For me it helped to change getAxisLabels to:
function axisLabels = getAxisLabels( handle )
axisLabels.x = get( get( handle, 'XLabel' ), 'String' );
axisLabels.y = get( get( handle, 'YLabel' ), 'String' );
axisLabels.z = get( get( handle, 'ZLabel' ), 'String' );
if iscell(axisLabels.x)
axisLabels.x = axisLabels.x{:};
end
if iscell(axisLabels.y)
axisLabels.y = axisLabels.y{:};
end
if iscell(axisLabels.z)
axisLabels.z = axisLabels.z{:};
end
end

Creating "spectrograms" (MATLAB: spectrogram) possible?

Hi,
unfortunately I am not able to convert matlab´s "spectrogram"-plot to TikZ.

Here is the MATLAB-code:

load chirp; %audio-file in vector 'y'
spectrogram(y,hann(1024),512,1024,Fs,'yaxis')

Here is a screenshot of matlab´s figure
http://s3.directupload.net/file/d/2133/j89ymchk_png.htm

matlab2tikz produces this tikz-file:

% This file was created by matlab2tikz v0.0.5.
% Copyright (c) 2008--2010, Nico Schlömer 
% All rights reserved.
%
% The latest updates can be retrieved from
%  http://win.ua.ac.be/~nschloe/content/matlab2tikz/
% and
%  http://www.mathworks.com/matlabcentral/fileexchange/22022 .
% where you can also make suggestions and rate matlab2tikz.

\begin{tikzpicture}
% Axis at [0.13 0.11 0.78 0.81]
\begin{axis}[
scale only axis,
width=4.82222in,
height=3.80333in,
xmin=0.0625, xmax=1.5,
ymin=0, ymax=4096,
xlabel={$Time$},
ylabel={$Frequency (Hz)$},
xmajorgrids,
ymajorgrids]
\end{axis}
\end{tikzpicture}

Would be a dream, if this kind of plot could be created by matlab2tikz

plot3/fill3 commands don't work properly

Hello there.

I've drawn a 2D sheet in a 3D enviroment (either with plot3 or fill3) and then exportir to tikz, but the program only generates a 3D plot. Here is a little example:

x1 = -10:0.1:10;
x2 = -10:0.1:10;
p = sin(x1);
d = zeros(1,numel(p));
d(2:2:end) = 1;
h = p.*d;
figure;hold on;grid on;
fill3(x1,x2,h,'k');
view(45,22.5);
matlab2tikz('Memoria.tex', 'height', '\figureheight',...
'width', '\figurewidth');

Or is there anything I'm doing wrong? I would appreciate any help.

Scatter plots

When I try to use matlab2tikz on scatter plots in Matlab 2010a I get the following error

??? Index exceeds matrix dimensions.

Error in ==> matlab2tikz>drawScatterPlot at 2041
str = strcat( str, ...

Error in ==> matlab2tikz>drawHggroup at 1942
[m2t,str] = drawScatterPlot( m2t, h );

Error in ==> matlab2tikz>handleAllChildren at 391
[m2t, env] = drawHggroup( m2t, child );

Error in ==> matlab2tikz>drawAxes at 777
[ m2t, childrenEnvs ] = handleAllChildren( m2t, handle );

Error in ==> matlab2tikz>saveToFile at 301
[m2t,env] = drawAxes( m2t, visibleAxesHandles(ix(k)), alignmentOptions(ix(k)) );

Error in ==> matlab2tikz at 232
saveToFile( m2t, fid, fileWasOpen );

Legend bug: wrong line width and color

First, let me say thank you for this great script!

I experience the following issue (on latest release and latest git source): I am drawing two plots with errorbar() and in addition add horizontal errorbars with the herrorbar() function from FileExchange (http://www.mathworks.com/matlabcentral/fileexchange/3963-herrorbar).

When I now add a legend to the graph, the little indicator lines before the legend text have the wrong line width and color.

Code to reproduce the issue:

figure
hold on
X = 1:10;
Y = 1:10;
err = repmat(0.2, 1, 10);
h1 = errorbar(X, Y, err, 'r');
h_vec = herrorbar(X, Y, err);
for h=h_vec
    set(h, 'color', [1 0 0]);
end
h2 = errorbar(X, Y+1, err, 'g');
h_vec = herrorbar(X, Y+1, err);
for h=h_vec
    set(h, 'color', [0 1 0]);
end
legend([h1 h2], {'test1', 'test2'})
hold off
matlab2tikz('test.tex');

determining scaling factor error

If you create a plot in matlab with custom ticks and labels, if there is only 1 specified tick at x/y/z=0 (for example when plotting only the x- and y-axes with no further grid), the matlab2tikz function of determining the scaling factor fails. Line 3851 of matlab2tikz.m is:

k = find( tick, 1 );

but find only looks for nonzero values. If there is only one value, and that is zero, this function returns an empty matrix. The next line then returns an error, because str2double can't work with nothing.

s = str2double( tickLabel{k} );

Should be easy to solve with an if-statement, I guess? I couldn't do it myself for now, as the value of k is also used in some further functions, but I will try to see if I can come up with a solution in code. Maybe someone who knows how the code works exactly could do it in a few seconds?

Regards, Luc

texthandling

Hi

I needed to change my parseTexSubstring() because I wanted to use an \omega in any label. Checking though the Text parsing the 'o' is recognized first instead of the complete word omega and out end up with a \o{}mega{} which cannot be teXed correctly ...

Cheers

Octave and CamelCase

Octave uses lower case for all its properties. Thus, the location info for colorbars and legends are all lower case, where Matlab's are CamelCase. I'll email a diff.

barplot does not work properly

First of all thanks a lot for that great tool! I just found it and the output in LaTeX looks like a figure in LaTeX should look like :) Unfortunately I have 2 problems with barplots. I created two small examples to demonstrate them. If you try this code in Matlab:

figure(1);
bins = -0.5:0.1:0.5;
hist1 = [0,6,9,14,12,5,3,1,0,0,0];
hist2 = [0,0,0,0,0,4,9,27,16,20,10];
bar(bins,[hist1;hist2]',2);
matlab2tikz( 'plot1.tikz', 'height', '\figureheight', 'width', '\figurewidth' );

and you then include plot1.tikz in LaTex then it shows some thicker bars that should not be there. As one result the overlapping area is not visible anymore.
Another problem that I have is the following:

figure(2);
bins = -0.5:0.1:0.5;
hist1 = [1,2,4,2,1,0,0,0,0,0,0];
bar(bins,hist1);
hold on;
hist2 = [0,0,0,0,0,1,2,4,2,1,0];
bar(bins,hist2);
matlab2tikz( 'plot2.tikz', 'height', '\figureheight', 'width', '\figurewidth' );

In this case there is a gab between the two histograms that should not be there. Can anyone help me with that?

bar plot legends misplaced

By [email protected]:

When converting a Matlab "bar()" plot with a legend, the tkiz-code is perfectly alright, except that the tikz-option "area legend" is missing. Without this keyword, there are no color boxes shown.

Code before:
...
\begin{axis}[%
scale only axis,
width=0.95\textwidth,
height=7cm,
xmin=0.5, xmax=3.5,
ymin=0, ymax=6,
ylabel={Normalized SSE per cell},
ymajorgrids,
legend entries={Fixed intervals,Streamline bundling before graph collapse,Streamline bundling after graph collapse,$\text{McKenzie with DuWang }(\text{Velocity influence }0.5)$,$\text{McKenzie with DuWang }(\text{Velocity influence }1.0)$,McKenzie with velocity only},
legend style={nodes=right}]
...

Code after (fixed directly within the tikz-script):
...
\begin{axis}[%
scale only axis,
width=0.95\textwidth,
height=7cm,
xmin=0.5, xmax=3.5,
ymin=0, ymax=6,
ylabel={Normalized SSE per cell},
ymajorgrids,
legend entries={Fixed intervals,Streamline bundling before graph collapse,Streamline bundling after graph collapse,$\text{McKenzie with DuWang }(\text{Velocity influence }0.5)$,$\text{McKenzie with DuWang }(\text{Velocity influence }1.0)$,McKenzie with velocity only},
legend style={nodes=right},
area legend]%THE CHANGE IS IN THIS LINE!
...

Corner case error in function splitByArraySize

When saving figures using matlab2tikz that have a number of points which is a multiple of 4000, an error is produced.

Example code:

x=1:4000;
y=rand(1, length(x)).*100;
plot(x, y, 'b+')
matlab2tikz('000.tikz', 'showInfo', false)

This yields the following error message in MATLAB:

??? Attempted to access xDataLeft(1,1); index out of bounds because size(xDataLeft)=[0,1].

Error in ==> matlab2tikz>splitByArraySize at 1447
      xDataExtra(end) = xDataLeft(1,1);

Error in ==> matlab2tikz>splitLine at 1098
      [xDataCell , yDataCell] = splitByArraySize( xDataCell, yDataCell );

Error in ==> matlab2tikz>drawLine at 930
          [xDataCell, yDataCell] = splitLine( m2t, xData, yData, xLim, yLim );

Error in ==> matlab2tikz>handleAllChildren at 420
              [m2t, env] = drawLine( m2t, child );

Error in ==> matlab2tikz>drawAxes at 731
  [ m2t, childrenEnvs ] = handleAllChildren( m2t, handle );

Error in ==> matlab2tikz>saveToFile at 335
      m2t = drawAxes( m2t, visibleAxesHandles(ix(k)), alignmentOptions(ix(k)) );

Error in ==> matlab2tikz at 266
  saveToFile( m2t, fid, fileWasOpen );

The same error occurs if x in the example above goes from 1 to 8000 or any other integer multiple of 4000. All non-multiples work fine (although obviously that wasn't tested exhaustively).

As a side note, the figure which originally showed this bug is quite a bit more complicated than the example given above (e.g. multiple plots within one figure) and the critical number of points for that plot is not 4000 but a seemingly arbitrary 5304. However, the root cause of accessing a certain element out of a 0x1 (empty) matrix remains the same, therefore I'm confident that fixing this bug for the example above also fixes it for my original figure.

dimension too large axis

I am not sure if this is a problem with matlab2tikz, or a problem with the plotting in MATLAB.

Take the short example

test=[-1e6,0;-1,1;-1,-1;-10,0];
plot(test(:,1),test(:,2),'.')
axis([-2,0,-2,2])

In the tikz file the axis is saved as it should be. However there are two problems with the points that fall outside the axis. Firstly, the point (-10,0) is recorded incorrectly as (-8.5,-0.166667), which is a problem if I want to come back and expand the axes later, but perhaps this is not one of the intended functions of matlab2tikz. The second more serious error is that the when compiling the error "dimension too large" appears. If the entry corresponding to (-1e6,0) is removed, then the document is able to be compiled.

Strict option throws error

Hi,

when using the current version(s) of matlab2tikz (version from github as of today or current package version from matlab file exchange), invoking matlab2tikz with the strict option set, throws the following error:

??? Undefined function or variable "str".

Error in ==> matlab2tikz>drawAxes at 721
str = [ str, ...

Error in ==> matlab2tikz>saveToFile at 301
[m2t,env] = drawAxes( m2t, visibleAxesHandles(ix(k)), alignmentOptions(ix(k)) );

Error in ==> matlab2tikz at 232
saveToFile( m2t, fid, fileWasOpen );

(using MatlabR2010b on 64bit Gentoo Linux, for a figure with standard xy grid lines enabled)

Changing the line to the " env.options = appendOptions( ... ) " style won't work, since (I assume) the corresponding pgfplots option "\pgfplotsset{every axis grid/.style={style=dotted}}" should be set before \begin{axis}

In case you can't repeat the error, I can post a small example.

Thanks,

Michael

wrong escaping of latex string

If I enter

\xlabel('\operatorname{Re}{\eta_n}');

matlab2tikz generates the following code which is not what I wanted

xlabel={$\text{$}\o\text{peratorname}{\text{Re}}{\eta{}_n}\text{$}$},

Did I use the wrong syntax or is this a bug ?

Empty XTickLabel and YTickLabel

matlab2tikz violates an empty XTickLabel or YTickLabel property of an axes element. Reproducable with the following MATLAB code:
clf
ax = axes();
plot( ax, rand(1,20), rand(1,20) );
set( ax, 'XTickLabel', [], 'YTickLabel', [] );
matlab2tikz( 'test.tikz' );

In Matlab, the X and Y ticks disappear, in LaTeX they appear.

To make the labels disappear is (at least for me) especially useful for stacking axes like in this code fragment:
fig = figure();
set( fig, 'Position', [50, 50, 530, 233 ] );
ax1 = axes( 'Parent', fig, 'Units', 'pixels', 'Position', [ 15, 20, 500, 100 ] );
ax2 = axes( 'Parent', fig, 'Units', 'pixels', 'Position', [ 15, 123, 500, 100 ] );
plot( ax1, 1:20, rand(1,20) );
plot( ax2, 1:20, rand(1,20) );
set( ax2, 'XTickLabel', [] );
matlab2tikz( 'stacked.tikz' );

cell string of title

The title of the plot might be stored as cell of strings in the figure. Therefore, I suggest to replace:

title = get( get( handle, 'Title' ), 'String' );

by:
title = get( get( handle, 'Title' ), 'String' );
if iscell(title)
title = title{:};
end

horizontal bar graphs barh

When matlab2tikz generates a tikz file for horizontal bar graphs generated using barh, it uses the option ybar instead of xbar. This is at least the case for me with MATLAB R2010a. Is this easy to fix?

Katherine

Plot order and axis background color

matlab2tikz isn't currently able to draw unaligned axes environments on the right positions.

To reproduce, plot the current script in MATLAB and in LaTeX:

wave = rand(1, 2048);
h = figure();
ax1 = axes( 'Parent', h );
ax2 = axes( 'Parent', h, 'Position', [0.5, 0.45, 0.35, 0.4] );
plot( ax1, wave );
plot( ax2, 1200:1500, wave(1200:1500) ); % Generates a "zoom window"
matlab2tikz( 'foo.tikz' );

syntax problem with cellstrs and Octave

With Matlab the syntax below works.

a = {'a'};
b = 'b';
a = [a, b];

In the 2nd line Matlab converts "b" from char to cell.

Octave does not (yet) do this. Either syntax below will work in both Octave and Matlab.

a = {'a'};
b = 'b';
a = [a, {b}];

or

a = {'a'};
b = 'b';
a = {a{:}, b};

Is that something that can be easily fixed?

contour plots

Contours that are not closed in the axis are not handled correctly. They are drawn as if the two visible end points were connected.

Axis labels default to math mode

The xlabel and ylabel automatically get surrounded with dollar signs. This is the opposite of the way MATLAB and LaTeX does it normally, and I think it would be make more sense to let the user insert dollar signs where appropriate.

Automatically add zlabel for surface/3d plots (if present)

The current version of m2t doesn't support zlabels if a label text has been set in MATLAB.

I'm not sure if this is the optimal method, but one way to include this feature is to change the following:

function axisLabels = getAxisLabels( handle )

  axisLabels.x = get( get( handle, 'XLabel' ), 'String' );
  axisLabels.y = get( get( handle, 'YLabel' ), 'String' );
  axisLabels.z = get( get( handle, 'Zlabel' ), 'String' );

end

to

function axisLabels = getAxisLabels()

  axisLabels.x = get( get( gca, 'XLabel' ), 'String' );
  axisLabels.y = get( get( gca, 'YLabel' ), 'String' );
  axisLabels.z = get( get( gca, 'Zlabel' ), 'String' );

end

and also add a an option for the zlabel/axis/ticks elsewhere in the m2t file where the above change requires additional changes.

Thus, when calling m2t on i.e. a surface plot where a zlabel is given, the tikz output will also have it.

I assume changing from handle to gca in the axisLabels function shouldn't affect any other parts of the output as we're converting the current plot anyways. If I in MATLAB give the surface plot a handle, i.e. h = surf(blabla); then get(get(h,'Zlabel'),'String') returns an error, wheras get(get(gca,'Zlabel'),'String') works fine.

br,
D.

Crossing lines in contour plots when multiple isolines at same contour level

For contour plots with multiple isolines at a given contour level the m2t script (as per today) connects this isolines, producing straight lines in the plot which shouldn't be there: take a look at first figure at XX

By sorting the data in the contour plot before writing it to the TikZ-file one may avoid this, look at second figure in same pdf (link above).

For this plot I've just used the the built in options for contour plots, and specifying how the format of the data is (compare XX and XX. *.dat file for pgfplots_result.tikz is also available at XX together with the sorting algorithm I used in MATLAB in order to do the sorting. If desirable to test for yourself, all other data and scripts for making it is also available in the same directory.

legend error

I just noticed that sometimes matlab2tikz sometimes breaks plots into two sets of plots. So I would have two \addplot commands for just one plot command in matlab.

While this is not a problem in itself, it causes a problem with legends. If I have plot A, and plot B, but I have 2 commands for plot A, then the legend will have the color of plot A twice.

Is anyone aware of what might cause matlab2tikz to break a plot into two pieces? If you need a sample figure I can provide one.

matlab2tikz does not support logarithmic colorbars (patch attached)

The following code results in wrong output with matlab2tikz (linear colorbar instead of logarithmic colorbar):

imagesc([1 10 100]); set(colorbar(), 'YScale', 'log'); matlab2tikz('test.tikz')

The following patch of matlab2tikz.m solves the problem:

2577a2578,2581

if strcmp(get(handle, 'YScale'), 'log')
env.name = 'semilogyaxis';
end

problems with the arguments

using matlab2tikz 0.0.7 I had the issues with the graphs being split into several plots as well so i tried the latest version from here. This works well concerning the mentioned issue, however there are some problems with the arguments passed to the script. mathmode is not allowed at all, this produces an error in myInputParser. height and width don't produce an error, but in the resulting files they are not recognized, instead for example the following is written in the tikz-file:
width=1width,
height=0.78871width,
I can fix this at the moment manually but in a release, this should be fixed.

btw, really a nice script :)

[bug] Empty tick labels disregarded in 0.1.4!

This is new bug introduced in 0.1.4 as far as I know.

Now, setting

set(gca,'YTickLabel',[])
set(gca,'YTick',[])

in MATLAB does not yield the desired result: y ticks are still attached to the graphics by pgfplots, as matlab2tikz fails at declaring the following axis option:

yticklabels={\empty}

This line was correctly being output by matlab2tikz in previous versions. I have to manually re-add it in my tex files.

Thank you

Sergio

Figure Size

Hi,

first of all thanks for this nice function for exporting matlab figures. When playing around with matlab2tikz (and comparing it to my previously used tool, laprint) I noticed one issue regarding the specification of the figure size, which I would like to share:

When I specify the desired width of the figure in the call to matlab2tikz like

matlab2tikz( 'figmatlab2tikz.tikz',width', '7.5cm', 'silent', true )

then in the latex document not the complete figure is 7.5cm wide but the x-axis is 7.5 cm wide.

Is there a way to specify the complete width of the figure in the call to matlab2tikz? Since I work frequently with latex documents in a 2 column format, specifying the complete width is really important.

Since I am not familiar with pgfplots or tikz, I am not sure how this might be possible. The only option I could think of is to use a resizebox command around the tikz file. But forcing the width using that command results also in scaled size of the fonts, something I would like to avoid.

On a side note, I would also welcome a more detailed explanation of the options. For example the consequences of "strict" to be true would be interesting.

Best,

Michael

Minor Things:

  • When "*** Make sure to load \usetikzlibrary{plotmarks} in the preamble." is printed, a newline command is missing at the end

string handling

I have previously used these strings for labelling plots:

xlabel('\text{time [s]}')
ylabel('\omega_\textit{eq} \text{ [p.u.]}')

which have in the past been translated to

$\text{time [s]}$
$\omega_\textit{eq} \text{ [p.u.]}$

by matlab2tikz, and this is just what I want.

It seems however that there has been a change in the string handling. These strings are now converted to

xlabel={$\text{\textbackslash{}text}{\text{time [s]}}$}
ylabel={$\omega{}_\text{textbackslash{}textit}{\text{eq}}\text{ \textbackslash{}text}{\text{ [p}.u.\text{]}}$}

I suppose that matlab2tikz now want s to sort out the formatting. However if I remove all formatting I get

xlabel={time [s]}
ylabel={$\omega{}_{\text{eq}}\text{ [p}.u.\text{]}$}

The xlabel is fine, but the ylabel is incorrect. I also don't see how I ever could have included the \textit formatting.

Is there some way to turn off this formatting, and go back to the way matlab2tikz used to handle strings? This may be a work in progress, but the old formatting was straightforward, and I liked it :)

Plot with one point only

Hi all,

first I'd like to thank you, Nico, for this great script. However, I discovered a bug...

Consider a simple plot with just one point, plotted as marker
plot(0.1, 0.1, 'x')

Then the tikz file does not have any coordinate written into, it only gets the axis definition from matlab2tikz('test.tikz'):
\begin{tikzpicture}
\begin{axis}[%
view={0}{90},
scale only axis,
width=3.07417in,
height=1.793in,
xmin=-1, xmax=1.5,
ymin=-1, ymax=1.5,
axis on top]
\end{axis}
\end{tikzpicture}

I nailed that down to the function "segmentVisible" where the output has always n-1 = 0 size, with n as the number of data points. Unfortunately I could not find a solution for handling just one point, and maybe you get that fixed faster.

Thanks and best regards

Sebastian

parseTeXString produces redundant spaces

Check out testfunctions(4): The TeX file contains \text{ sin} where it should be \text{sin}.
The parser itself is pretty involved aka hardly readable; all those regexes! We might think about a rewrite sometime...

Bar plots

It appears that matlab2tikz doesn't support bar plots.

I'm using Matlab R2009b on Windows XP. Here's a log.

>> bar([10 20]); matlab2tikz( 'myfile.tikz' );

 *** 
 *** This is matlab2tikz v0.0.6.
 *** The latest updates can be retrieved from
 *** 
 ***   http://www.mathworks.com/matlabcentral/fileexchange/22022-matlab2tikz
 *** 
 *** where you can also make suggestions and rate matlab2tikz.
 *** 
 *** matlab2tikz uses features of Pgfplots which may be available only in recent version.
 *** Make sure you have at least Pgfplots 1.3 available.
 *** For best results, use \pgfplotsset{compat=newest}, and for speed use \pgfplotsset{plot     coordinates/math parser=false} .
 *** ??? Attempted to access m2t.barShifts(1); index out of bounds because
numel(m2t.barShifts)=0.

plotyy problem

another problem: i want do a bodeplot with gain and phase in one diagram, hence using plotyy. In Matlab everything looks fine, y-axis on the left for gain, y-axis on the right for phase and one x-axis on the bottom for time. All axises with labels. That's how it looks fine for me and i would like to have it.
But after converting to tikz, there is an additional x-axis at the top (it's just the numbers at the ticks i don't like) and much worse the labels for both y-axises are on the left side overlapping each other. I already had a look into the tikz-file and played around a little bit, but i hardly know the syntax of pgfplots so i don't even know if it is easy to implement how i think it should be.

legends in subplots

Hi,

in the following example only the bottom subplot should have a legend. But instead both subplots have the same legend:

figure()
subplot(2,1,1)
plot(1,1)
subplot(2,1,2)
plot(1.5,2)
legend('test')
matlab2tikz('filename','test.tikz','height','\figheight','width','\figwidth')

TickLabel handling

in getTicks() I had a little problem ...

MATLAB(R) Help says:
Note that tick labels do not interpret TeX character sequences (however, the Title, XLabel, YLabel, and ZLabel properties do).

Now this may be awful if you like to place e.g. pi/2;p;3pi/2 labels on a sine plot ...

I just tweaked the labelInterpreter to 'tex' and had to make sure the ticks are stored in cell arrays. My Code now looks like this:
.......
xTickLabel = get( handle, 'XTickLabel' );
if ~iscellstr(xTickLabel)
xTickLabel = cellstr(xTickLabel);
end
for k = 1:length(xTickLabel)
xTickLabel{k} = prettyPrint( m2t, xTickLabel(k), labelInterpreter);
end
xTickMode = get( handle, 'XTickMode' );
.......
And this for all directions, works for me.

Cheers

Possibility to add extraEnvOptions (similar to extraAxisOptions)?

Since I still don't get the pull request thing 100%:

Possible to add something like

% extra environment options
m2t.cmdOpts = m2t.cmdOpts.addParamValue( m2t.cmdOpts, 'extraEnvOptions', {}, @isCellOrChar );

and add

if ~isempty( m2t.cmdOpts.Results.extraEnvOptions )
    m2t.content = append( m2t.content, m2t.cmdOpts.Results.extraEnvOptions );
end

below the line

m2t.content.name = 'tikzpicture';

This way, it's easier to add extra options to the tikzpicture environment that should be placed outside the axis environment without having to edit each file manually.

Support truecolor images and indexed images with >256 colors (patch attached)

The used export file format PNG is limited to 256 colors with indexed colors (http://en.wikipedia.org/wiki/Portable_Network_Graphics#Color_depth). Thus indexed color images in Matlab with more than 256 colors cannot be used with matlab2tikz.
The following code demonstrates that:
%figure; imagesc(repmat(1:1024, [2 1])); colormap(jet(1024)); colorbar()

The current drawImage code always uses indexed colors, independently of the fact, that the image in Matlab may be a truecolor image, leading to the same limitations.
The following code demonstrates that:
%figure; imagesc(repmat(shiftdim(jet(1024), -1), [2 1])); colormap(jet(1024)); colorbar()

Both issues apply on colorbars, as well.

The following patch fixes all these problems:

  • Indexed color images with more than 256 colors are transformed to truecolor images, because that is normally, what a user wants: export the image as shown in Matlab (instead of resulting in an error or reducer the number of colors).
  • Truecolor images are treated and exported as truecolor images
  • Do the same with colorbars (thus the new function imwriteWrapperPNG has been introduced to avoid code duplication)

This is the git-patch, which should apply to 1d7490b. Apart from the introduction of the new function there are mostly needed whitespace changes and some syntactic sugar, as cdata and colorData can now be 2-dimensional (indexed color) or 3-dimensional (truecolor).

diff --git a/src/matlab2tikz.m b/src/matlab2tikz.m
index 8e25cda..4609b6e 100644
--- a/src/matlab2tikz.m
+++ b/src/matlab2tikz.m
@@ -1793,7 +1793,7 @@ function [ m2t, str ] = drawImage( m2t, handle )
% Flip the image over as the PNG gets written starting at (0,0) that is,
% the top left corner.
% MATLAB quirk: In case the axes are invisible, don't do this.

  •  cdata = cdata(m:-1:1,:);
    
  •  cdata = cdata(m:-1:1,:,:);
    

    end

    if ( m2t.opts.Results.imagesAsPng )
    @@ -1803,31 +1803,35 @@ function [ m2t, str ] = drawImage( m2t, handle )
    [pathstr, name ] = fileparts( m2t.tikzFileName );
    pngFileName = fullfile( pathstr, [name '.png'] );
    pngReferencePath = fullfile( m2t.relativePngPath, [name '.png'] );

  •  colorData = zeros( m, n );
    
  •  % TODO Make imagecolor2colorindex (or getColor for that matter) take matrix
    
  •  %      arguments.
    
  •  for i = 1:m
    
  •      for j = 1:n
    
  •          % Don't use getImage() here to avoid 'mycolorX' constructions;
    
  •          % exclusively color index data needed here.
    
  •          [ m2t, colorData(i,j) ] = imagecolor2colorindex ( m2t, cdata(i,j), handle );
    
  •  % Get color indices for indexed color images and truecolor values otherwise.
    
  •  if ndims( cdata ) == 2
    
  •      colorData = zeros( m, n );
    
  •      % TODO Make imagecolor2colorindex (or getColor for that matter) take matrix
    
  •      %      arguments.
    
  •      for i = 1:m
    
  •          for j = 1:n
    
  •              % Don't use getImage() here to avoid 'mycolorX' constructions;
    
  •              % exclusively color index data needed here.
    
  •              [ m2t, colorData(i,j) ] = imagecolor2colorindex ( m2t, cdata(i,j), handle );
    
  •          end
       end
    
  •  else
    
  •      colorData = cdata;
    

    end

    % flip the image if reverse
    if m2t.xAxisReversed

  •      colorData = colorData(:,n:-1:1);
    
  •      colorData = colorData(:,n:-1:1,:);
    

    end
    if m2t.yAxisReversed

  •      colorData = colorData(m:-1:1,:);
    
  •      colorData = colorData(m:-1:1,:,:);
    

    end

  •  cmap = get(m2t.currentHandles.gcf, 'ColorMap');
    
    • % write the image
  •  imwrite( colorData, ...
    
  •           get(m2t.currentHandles.gcf,'ColorMap'), ...
    
  •           pngFileName, ...
    
  •           'png' ...
    
  •         );
    
  •  imwriteWrapperPNG ( colorData, cmap, pngFileName );
    

    % ------------------------------------------------------------------------

    xLim = get( m2t.currentHandles.gca, 'XLim' );
    @@ -2742,7 +2746,7 @@ function [ m2t, env ] = drawColorbar( m2t, handle, alignmentOptions )
    xLim = [0,1];
    yLim = clim;
    end

  •  imwrite( strip, cmap, pngFileName, 'png' );
    
  •  imwriteWrapperPNG( strip, cmap, pngFileName );
    

    env = append( env, ...
    sprintf( '\addplot graphics [xmin=%d, xmax=%d, ymin=%d, ymax=%d] {%s};\n', ...
    xLim(1), xLim(2), yLim(1), yLim(2), pngReferencePath) ...
    @@ -4621,3 +4625,26 @@ end
    % =========================================================================
    % *** END FUNCTION printAll
    % =========================================================================
    +
    +% =========================================================================
    +% *** FUNCTION imwriteWrapperPNG
    +% =========================================================================
    +function imwriteWrapperPNG( colorData, cmap, fileName )

  • % Write an indexed or a truecolor image

  • if ndims( colorData ) == 2

  •    % According to imwrite's documentation there is support for 1-bit, 2-bit, 4-bit
    
  •    % and 8-bit indexed images only. In practice, indexed images with up to 256
    
  •    % colors work.
    
  •    % When having more colors, a truecolor image must be generated and used instead.
    
  •    if size( cmap, 1 ) <= 256
    
  •        imwrite ( colorData, cmap, fileName, 'png' );
    
  •    else
    
  •        imwrite ( ind2rgb(colorData, cmap), fileName, 'png' );
    
  •    end
    
  • else

  •    imwrite ( colorData, fileName, 'png' );
    
  • end
    +end
    +% =========================================================================
    +% *** END FUNCTION imwriteWrapperPNG
    +% =========================================================================

Regression in moveToBoundingBox()

Commit dc267fa (increase the bounding box limits to +-164) introduced a regression in the function moveToBoundingBox(). When using this version or any of the ones thereafter the following code produces an error:

addpath('path/to/matlab2tikz/src')
x=1:199;     % 1:99 => no error
y=rand(length(x), 1);
figure
plot(x, y, 'b+')
matlab2tikz('000.tikz', 'showInfo', false)

The error message in MATLAB is as follows:

??? Error using ==> matlab2tikz>moveToBoundingBox at 1583
Could not determine were the outside point sits with respect to the box. Both x and xRef outside the
box?

Error in ==> matlab2tikz>splitByOutliers at 1410
              new = moveToBoundingBox( outData, ref, xLimLarger, yLimLarger );

Error in ==> matlab2tikz>splitLine at 1176
      [xDataCell , yDataCell] = splitByOutliers( xDataCell, yDataCell, xLim, yLim );

Error in ==> matlab2tikz>drawLine at 1015
          [xDataCell, yDataCell] = splitLine( m2t, xData, yData, xLim, yLim );

Error in ==> matlab2tikz>handleAllChildren at 420
              [m2t, env] = drawLine( m2t, child );

Error in ==> matlab2tikz>drawAxes at 892
  [ m2t, childrenEnvs ] = handleAllChildren( m2t, handle );

Error in ==> matlab2tikz>saveToFile at 335
      m2t = drawAxes( m2t, visibleAxesHandles(ix(k)), alignmentOptions(ix(k)) );

Error in ==> matlab2tikz at 266
  saveToFile( m2t, fid, fileWasOpen );

A similar error is reported when using Octave. Note that whether or not the error occurs depends on the size of x. A vector from 1 to 99 did not produce an error in any of my experiments whereas a vector ranging from 1 to 199 always did. I didn't try to come up with the precise cut-off point.

The example code above does work when using the version from commit 6fc70d9 (the one before the regression was introduced).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.