File Exchange

image thumbnail

Scalable Vector Graphics (SVG) Export of Figures

version 1.9.0 (807 KB) by Juerg Schwizer
Converts 3D and 2D MATLAB plots to the scalable vector format (SVG).


Updated 23 Apr 2021

From GitHub

View Version History

View license on GitHub

Editor's Note: This file was a File Exchange Pick of the Week

Scalable Vector Graphics (SVG) Export of Figures

Converts 2D & 3D Matlab plots to the scalable vector format (SVG). This format is specified by W3C ( and can be viewed and printed with internet browsers.

Added preliminary support of filter, clipping, and tickmark extensions that go beyond the Matlab functionality. SVG filters are a great tool to create stylish plots! Try it out! Before you start using this new features have a look at the tutorial.

Editors for the SVG file format can be found at

> plot2svg % opens a file dialog to plot the active figure
> plot2svg('myfile.svg', figure handle, pixelfiletype)

pixelfiletype = 'png' (default), 'jpg'

Supported Features
- line, patch, contour, contourf, quiver, surf, ...
- markers
- image (saved as linked png pictures)
- grouping of elements
- alpha values for patches
- subplot
- colorbar
- legend
- zoom
- reverse axes
- controls are saved as png pictures
- log axis scaling
- axis scaling factors (10^x)
- labels that contain Latex commands are interpreted (with some limitations):
\alpha, \Alpha, \beta, \Beta, ... \infity, \pm, \approx
{\it.....} for italic text
{\bf.....} for bold text
^{...} for superscript
_{...} for subscript

How to use SVG files in HTML code
<object type="image/svg+xml" data="./mySVGfile.svg" width="140" height="100"></object>

- Does not support figure objects that have been introduced for > Matlab R2014b
- axis scaling factors for 3D axes
- 3D plot functionality limited (depth sorting, light)

Cite As

Juerg Schwizer (2021). Scalable Vector Graphics (SVG) Export of Figures (, GitHub. Retrieved .

Comments and Ratings (207)

Querusche Zanona

Great tool.
Limitation: panel.


Alexis Shakas

My first review - I just had to, because this is a great tool !

Alex Wyatt

avlas didra

I would like to let you know about fig2svg toolbox: a Matlab/GNU Octave FIG to SVG converter (

The most important feature when comparing fig2svg to plot2svg is that fig2svg has enhanced compatibility, especially for Matlab graphics > 2014a.

Updated Features

- bar plot
- scatter plot
- legend
- colorbar
- ticklabelrotation
- annotations
- 3D plots (distinct azimuth values)

Current Limitations:
- horizontal bar plot
- stairs and stem plots
- patch enhancements
- 3D plots (distinct elevation values)
- your feature request ;-)

fig2svg was originally a fork of plot2svg currently unmaintained

Yair Altman

Note: While Juerg Schwizer's plot2svg was last updated in 2015 (, a more recent version (fork) of plot2svg can be found in, and unlike Juerg's original version Kupiqu's version seems to be actively maintained.

Yair Altman

@Martin - the version of plot2svg on the Matlab File Exchange is relatively old (2012) compared to the latest one on Github (<a href=" -2015), so I suggest that you download from Github.

My personal experience is that plot2svg may be better than Matlab's SVG export, fixing some of its bugs. For example, the bug with the tex/latex axes labels that is described here:

Martin Dawson

Probably very useful when it was created, but now Matlab can save directly as an svg, and Matlabs standard has changed so much that this function needs alto of modification to run. I found getting it to run with scatter plots was fairly easy, but hadn't managed to get it to read axis labels or legends before deciding to use the inbuilt svg save in Matlab.

Frantisek Pernis

Warning: Unhandled child type: implicitfunctionline

Avisha NessAiver

For those having the "Requires character vector array input" error in R2017a /b, if you go in and change the lines that say "str2num(get(ax,'YTickLabel'));" and "str2num(get(ax,'XTickLabel'));" to read "str2num(char(get(ax,'YTickLabel')));" it should fix it. (Somewhere around line 2454).

Mark T

Many thanks for your work on this - very useful.
An (esoteric) side note to any CorelDRAW users: if you use Matlab to make curves for import to CDR (as PDF), you may have noticed there is some kind of limit to the number of nodes before CDR makes separate curve segments... this can make problems. Importing SVG, e.g. made with this m-file here, doesn't seem to suffer from this problem.

qingbin meng

Dominik Puckert

Same problem as the previous comment (R2017a). Not even the demo works.

Error using str2num (line 31)
Requires character vector or array input.

Error in plot2svg>exponent2svg (line 2454)
numlabels = str2num(get(ax,'YTickLabel'));

Error in plot2svg>axes2svg (line 1321)

Error in plot2svg (line 243)

Error in demo_svg_water (line 76)

Will Lykins

I'm running R2017a and I keep getting these errors when I try to run with a pretty basic line plot:
Error using str2num (line 31)
Requires character vector or array input.

Error in plot2svg>exponent2svg (line 2429)
numlabels = str2num(get(ax,'XTickLabel'));

Error in plot2svg>axes2svg (line 1321)

Error in plot2svg (line 243)

As far as I can tell all the parameters being called are correct. And after some testing, it doesn't have anything to do with the properties of the plot

Manjunath Navalgund

Authors should really include a how to / readme instructions.
I will be a great great help for the beginners
I really have no idea how this works ....I am just getting tons of errors

Victor Yashunsky

Please advice how to export quiver plot
Keep getting the following message
"Warning: Unhandled child type: quiver"

Jon Matthis

I get the following error, any advice?

>> plot2svg('myfile.svg', gcf)

Matlab/Octave to SVG converter version 15-Sep-2012, Juerg Schwizer (

Warning: Unhandled child type: contour

Error using str2num (line 32)
Requires string or character array input.

Error in plot2svg>exponent2svg (line 2454)
numlabels = str2num(get(ax,'YTickLabel'));

Error in plot2svg>axes2svg (line 1321)

Error in plot2svg (line 243)


Justin Baik

Great for plotting any graph with transparent color components! I absolutely love how my plots look.

Only thing I am having trouble is that it will actually not write the axes labels. I tried a few things, but it just won't do in the new 2016b version. I tried running the sample codes. It wouldn't take the legend handle and also the title and the axes labels are missing.

Andres Montano


Milz Dag

Thanks for a nice tool.

On my end, error bars overlaid on a mesh are not being reproduced properly on my end. The error bars are either on top the surface or completely hidden below (they should be half n' half, i.e. sticking out). Everything else working fine so I'm assuming that's a bug/limitation? Thanks!

Sandor Toth

Unfortunately the exported example svg file of demo_3d_plot2svg.m has an error, it cannot be opened in Adobe Illustrator and when opened in Safari I get the following error message:
error on line 11184 at column 1: Extra content at the end of the document

I am testing the code on Matlab R2016b.

Tomas Zegard

--- Newer versions of MATLAB may give the following error message:

Subscript indices must either be real positive integers or logicals.

Error in plot2svg>axchild2svg (line 1589)
patch2svg(fid, group, axpos, x(faces(p,:)), y(faces(p,:)), facecolorname, linestyle, linewidth, edgecolorname, face_opacity, edge_opacity, closed)

Error in plot2svg>axes2svg (line 1062)
group = axchild2svg(fid,id,axIdString,ax,group,paperpos,axchild,axpos,groupax,projection,boundingBoxAxes);

Error in plot2svg (line 243)

--- To solve, replace lines 1588-1590 with the following kludge:
if flat_shading
patch2svg(fid, group, axpos, x(faces(p,:)), y(faces(p,:)), facecolorname, linestyle, linewidth, edgecolorname, face_opacity, edge_opacity, closed)
face_aux = faces(p,:);
face_aux = face_aux(isfinite(face_aux));
patch2svg(fid, group, axpos, x(face_aux), y(face_aux), facecolorname, linestyle, linewidth, edgecolorname, face_opacity, edge_opacity, closed)


Legend is not supported. Always "Warning: Unhandled main figure child type: legend"

otherwise would be a good function

Yupeng li

Thomas Fastl


you've created an absolutely amazing tool, thank you soo much! I'm mainly using this code to generate .svg files for retouching Matlab figures in Inkscape.

I've just recently realized one issue I'm not sure how to handle, maybe someone else can help. I'm generating a histogram using bar(range,histogram,'histc'), where the bars have no spaces between them. However, after exporting the figure and importing it into Inkscape one can clearly see that the bars aren't touching anymore.

Any help on that would be appreciated and thanks again for your great work!


Karsten Kuhlmann

Hi, great tool! I used it a lot in the past. But is there a way to get rid of the white border (cropping) in the svg file? The way 'export_fig' (see Matlab file Exchange) does e.g.? Now I delete the border in inkscape, but if you generate many files automatically, you have to do it all over if one parameter changes.


Nevermind, I threw in a colorcheck in line2svg for the color my custom grid uses. Checking the 4th element of the color somehow didnt work.


Hi, thanks very much for this script, its the only option to export transparent patches without visual errors for me. However, I am using gridxy to draw custom grid lines. These are drawn as lines but not flagged as gridlines internally it seems [c&p from gridxy script: np = get(hca,'nextplot'); set(hca,'nextplot','add'); h = line('xdata',xx1(:),'ydata',yy1(:));].

I have set their transparency to 0.15 by adding it to the rgb triplet as 4th entry. This seems not to be checked when converting though (I cannot set GridAlpha with gridxy). I tried switching the default GridAlpha in your script from 1 to 0.15 (which actually is Matlabs default, so you may wanna update that) and at least have transparent regular (using grid on) gridlines now. I still can't use gridxy however.

Could someone with more coding knowledge than me give me a hint where in the code I would have to look to set the alpha value of regular line objects? Or even provide a solution? Thanks in advance.


You are a life saver. Thank you so much !

will wehner

How can this be used for animations?

Peter Griffin

Hi All,
I'm trying to save a plot with a transparent cone and a non-transparent plane. I'm using the 'hold on'-command to plot the two surfaces in one figure, but plot2svg is stacking the plots on top of each other. Therefore, one plot is covered up by the other. How can I fix this? Thanks.

Hello Fellows. Hopefully u r fine. I have to display the Plot of Plot2svg in BLACK Color. So What amendment I have to make in code to make it visible in Black. Thanks for helping me.

Paul Macey

I used this to export a transparent patch. In MATLAB 20016a, I had to change plot2svg.m around lines 2449 - 2459:

This line gives an error:
numlabels = str2num(get(ax,'YTickLabel'));

The fix is simple:
if PLOT2SVG_globals.octave
% Octave stores YTickLabel in a cell array, which does not work nicely with str2num. --Jakob Malm
axlabely = get(ax, 'YTickLabel');
numlabels = zeros(length(axlabely), 1);
for ix = 1:length(axlabely)
numlabels(ix) = str2num(axlabely{ix});
numlabels = str2num(get(ax,'YTickLabel'));

axlabely = get(ax, 'YTickLabel');
numlabels = zeros(length(axlabely), 1);
for ix = 1:length(axlabely)
numlabels(ix) = str2num(axlabely{ix});

For those interested, to get a transparent patch into CorelDraw, where is my process:
* create figure in MATLAB with transparent patch
* save as svg file with plot2svg
* Open in Inskape (free - Google it to download)
* Optionally, edit to remove un-needed objects
* Save as eps
* Import eps into CorelDraw

CorelDraw does not import svg (crashes), and Illustrator fails as well. Copying and pasting as metafiles from MATLAB does not work in CorelDraw or Illustrator. Exporting to pdf, either with MATLAB print command or export_fig, adn importing pdf into CoreldDraw, does not work (the patches come out as lines in the pdf). Copy from Inskape and past into CorelDraw does not work.


I am using multiple layers in a plot with the commandes uipanel and uistack. However, plot2svg does not handle this kind of object. Is it possible to fix it ?


Has anybody found a workaround yet for the legend/colorbars not appearing as of 2014b? (I am using 2015b, but I think it came along with the major change in 2014b making legends and colorbars separate objects rather than axes)

Vincent Prevosto

Felipe: you can solve this issue easily by adding a new markeredgecolor case line 1579:
case 'auto' %new Matlab color schemes markeredgecolor=get(gcf,'colormap');
markeredgecolor=markeredgecolor(i,:); markeredgecolorname=searchcolor(id,markeredgecolor);
But I suggest you check Juerg's most recent version at

Marcel Beining

Minor Bug report:
if one wants to define pixelfiltertype, but leaves out specifying the figure handle id, there is an error. fixed by adding "|| isempty(id)"

Felipe BM

Thanks Juerg for this great tool.
Recently I'm getting this error message when trying to use plot2svg in a line plot figure:
Unsupported color handling for patches
Can you tell the reason? How to solve it?

Thanks again!


In Matlab 2014b:

Unhandled (main figure) child type: Legend (Bar)

The provided 'background images' (*.jpg) are not incorporated in the *.svg output

Carl Wouters

Some functions not working for v R2015a.
For example scatter, colorbar

I changed the code to instead of generating a file, it gives the svg text as output.


Somehow, the LaTeX greek \phi appears as \varphi in the legend.


I have a problem when plotting data at a sphere. Even if i'm plotting a white sphere inside (via surface...) in the export it looks transparent, so that also the data from the other side of the sphere is visible. Is there any way to prevent the sphere from being transparent (in Matlab itself, it is not transparent, all the alpha values are set accordingly). Thanks.

Durga Lal Shrestha

It is pity that plot2svg does not support legend in MATLAB R2014b.

Juerg Schwizer

To all Matlab R2014b users:

As the graphic engine of Matlab R2014b contains major changes some functionality is no more compatible. The svg format is finally supported natively. Unfortunately, the resulting files are sometimes very big. The latest version of plot2svg can be found on git

The current version available contains first changes needed for Matlab R2014b support. Please also report bugs there.


Dear Juerg, thanks for this great contribution. Are you still interested in bug fixes?

If the axes are in log scale, only the minor grids lower than the biggest tick are plotted. However, if you want to continue the minor grid, you can replace

axxtick = log10(get(ax,'XTick'));
minor_axxtick = [];
if ~isempty(axxtick_w)
all_axxtick = axxtick(1):1:axxtick(end);
for stick = all_axxtick
minor_axxtick = [minor_axxtick minor_log_sticks + stick];
minor_axxtick = minor_axxtick(find(minor_axxtick > min(axlimx) & minor_axxtick < max(axlimx)));

around line 940 with

axxtick = log10(get(ax,'XTick'));
minor_axxtick = [];
%if ~isempty(axxtick_w)
%all_axxtick = axxtick(1):1:axxtick(end);
all_axxtick = ceil(min(axlimx)):1:ceil(max(axlimx));
for stick = all_axxtick
minor_axxtick = [minor_axxtick minor_log_sticks + stick];
minor_axxtick = minor_axxtick(find(minor_axxtick > min(axlimx) & minor_axxtick < max(axlimx)));

(and for the y and z axis respectively). I personally consider this as a bug, but maybe this original behavior was intended.


Dear Juerg,
First, i would like to thank you for sharing a great tool.

I have the following problem with a figure of dimension 3 could you help me to fix it please!

Subscript indices must either be real positive integers or logicals.

Error in plot2svg>axchild2svg (line 1481)

Error in plot2svg>axes2svg (line 1062)
group = axchild2svg(fid,id,axIdString,ax,group,paperpos,axchild,axpos,groupax,projection,boundingBoxAxes);

Error in plot2svg (line 243)

Thanks a lot


Same as Richard, i have the "Warning: Unhandled main figure child type". If anybody has a fix...

Neil Dalchau

This is a brilliant contribution. Thank you!

I have found a bug with reproducing textbox annotations. The left-hand edge is not reproduced. A simple example is:

annotation('textbox',[0.2 0.3 0.6 0.4],'String','test')

Bauyrzhan Aubakir

Can I suggest Adding support of svg(html) links?


Hi All

I have an issue getting plot2svg working on matlab 2014b, whereas it worked perfectly before.

Initially I had the some problem as Mirko, but I was able to fix it using the comments below. I now get the following errors:

Warning: Unhandled child type: contour
Warning: Unhandled main figure child type: colorbar

The code produces an svg file but the axes are empty and there is no colorbar.



Sorry, my fault, I fixed the error thanks to Jeff suggestion.


I'm using this function since long time ago, but now I upgrated matlab to R2014b version and it isn't working anymore!

I get this msg error:

Error using str2num (line 32)
Requires string or character array input.

Error in plot2svg>exponent2svg (line 2429)
numlabels =

Error in plot2svg>axes2svg (line 1321)

Error in plot2svg (line 243)



Evidently str2num used to work on cell arrays? To get it to work I had to change line 2451 from
numlabels(ix) = str2num(axlabely{ix});
numlabels(ix) = str2double(axlabely{ix});

Otherwise, it does just what I need, thanks!


One of my favorites. Thank you


I tried your code, and it works for me.

text(1 ,0.5,0,'{\bf TEST}','Interpreter','latex','Rotation',90);

Durga Lal Shrestha

It seems the plot2svg does not support bold font for label and texts. It is said in description of the script that Latex commands are interpreted (with some limitations). I tried
text(1 ,0.5,0,'{\bf TEST}','Interpreter','latex','Rotation',90);

But it does not produce bold font. Is there any solution to produce bold font?

Alessandro Masullo

I really love this script but I have to report a bug dealing with squared scatter plot.

It can be easly reproduced by:


it yields this error:

Undefined function or variable "linex".

Error in plot2svg>axchild2svg (line 1630)
case {'square', 's'},group=group+1;patch2svg(fid,group,axpos,xmarker'*ones(1,5)+ones(length(linex),1)*[-1 -1 1 1
-1]*markersize,ymarker'*ones(1,5)+ones(length(liney),1)*[-1 1


Is there an easy way to use this function for figures where the colormap has more than 256 colors?

Sinan Teske

If I rotate the view of a 3D-Plot with view(5,10) for example, the TickMarks and the TickLabels are wrong in length and positioning, respectively.

Would be nice if a fix for that could be provided. ZLabelTick should maybe always point horizontally or sizing should be view dependend.

Also marks at the corners of the were clipped so I had to enlarge the bounding Box of the axes by changing line 759
% boundingBoxAxes = [min(x) min(y) max(x)-min(x) max(y)-min(y)];


boundingBoxAxes = [min(x)-0.1*min(x) min(y)-0.1*min(y) max(x)+0.1*max(x)-min(x) max(y)+0.1*max(y)-min(y)];

Additionally in the adchild2svg function
under line
elseif strcmp(get(axchild(i),'Type'),'patch')

I had to add
linex = get(axchild(i),'XData');
liney = get(axchild(i),'YData');
linez = get(axchild(i),'ZData');

to support other marker types such as diamonds of scatter3 generated markers.

But thanks for this great Tool!!

This works really well.
It's a mystery to me, though, why you scale circle-markers to 0.75 of MarkerSize. It makes plots with different marker-types less coherent.

Easily 'fix'able, though: In plot2svg.m, L.1409, replace 0.75 with 1.

Pulkit Budhiraja


I was looking for something like this for weeks

Sebastian Hölz

I experienced some problems when exporting a figure with a map containing a true color image. Upon export the "linked" image was plain empty. I could track this down to line 2024 of the code "imwrite(pointc, ..."

pointc is changed to double (n x m x 3) a few lines above. If you cast it back to uint8, the imwrite command works as expected (i.e. "imwrite(uint8(pointc), ..."

I don't know if this is a case in plot2svg, which is just not handled or maybe if the imwrite command has changed.



you should learn Matlab:
plot2svg([fileName '.svg']);


This has saved me days in exporting MATLAB figures!


I have many ".fig" files in a folder (say one.fig, two.fig ...etc). I want to convert all of them into ".svg" files (say one.svg, two.svg ...etc) using "plot2svg". I came up with this script:

function myfun = test
dirListing = dir('*.fig');
for d = 1:length(dirListing)
fileName = dirListing(d).name;

This will open all ".fig" files in the folder, but save all the figures with the same file name i.e. "fileName.svg". This is because "plot2svg" takes the "fileName" literally instead of taking the dynamic BASE name (without extension, a bonus) of the file from "fileName = dirListing(d).name;".

What is the workaround? How to make "plot2svg" take dynamic base name of the files?


Hi All,

i've also got a kickout at line 1630 with:

Matlab/Octave to SVG converter version 15-Sep-2012, Juerg Schwizer (
Undefined function or variable "linex".

Error in plot2svg>axchild2svg (line 1630)
case {'square',
-1 1 1 -1]*markersize,ymarker'*ones(1,5)+ones(length(liney),1)*[-1 1
Error in plot2svg>axchild2svg (line 2075)

Error in plot2svg>axes2svg (line 1062)
group =

Error in plot2svg (line 243)

I was exporting scatter plots to SVG.

The patch is to add the lines just after the line 1462:

% edited by ejs, 2013-09-18
linex = get(axchild(i),'XData');
% Octave stores the data in a column vector
linex = linex(:)';
if strcmp(get(ax,'XScale'),'log')
linex(find(linex<=0)) = NaN;

% Octave stores the data in a column vector
liney = liney(:)';
if strcmp(get(ax,'YScale'),'log')
liney(find(liney<=0)) = NaN;

% Octave stores the data in a column vector
linez = linez(:)';
if isempty(linez)
linez = zeros(size(linex));
if strcmp(get(ax,'ZScale'),'log')
linez(find(linez<=0)) = NaN;
% end edited by ejs

Hope it will not negatively affect the entire code ;)


Best function since 'plot();'!
Saves my scientific career. Thank You!

Emmanuel Farhi

An excellent export to a vectorial multi-platform format. Thanks.

Noah Levine-Small

Hey mate. Thanks for submitting such a useful function. :) I think I've found a small bug. Minor tick axes don't appear in the SVG if you are using log scale axes...They do appear in Matlab and if I export to PDF and then import into Inkscape.

Jeroen Oomkes

I tested with this figure and get 'Index exceeds matrix dimensions' error. I fixed this by replacing

for i = 1:length(axxindex)
for i = 1:length(axlabelx)



Bharath Lohray

I get SVGs that have the wrong stacking order - The shadows (the countours on the plot floor for a 3d mesh plot) are above the objects instead of below the object.

see: - The generated svg

Chuntao Dan

Hi, this seems to be very useful. However, I get an error when there're scattered asterisk in the figure:

Undefined function or variable "linex".

Error in plot2svg>axchild2svg (line 1627)
case '*',group=group+1;patch2svg(fid,group,axpos,xmarker'*ones(1,11)+ones(length(linex),1)*[-1 1 NaN 0 0 NaN -0.7
0.7 NaN -0.7 0.7]*markersize,ymarker'*ones(1,11)+ones(length(

Does anyone know how to fix it? Thanks.

Nam Tran

the script works fine.
But sometime i have problem with the ylabel. It is too close the the Y-Axis, and the long label can overlap with the scale. The X-label too.
Does anyone know how to fix it ?


Thank you for this great tool !

However I encounter a problem when I use alpha on image. For exemple with this kind of code:

>> % SVG converter version 15-Sep-2012
>> figure
>> colormap(hsv)
>> image(randi(100,10,10)),
>> alpha(double(rand(10,10)))
>> plot2svg('test.svg',gcf,'png')

In the svg file, the transparency has disapeared.

Is there a way to fix it ?
Thank you

Shuhao Cao

Greg Hale

Thanks Juerg. Any plans to support hgtransform? My hgtransformed' plots in matlab aren't getting moved to the right places.


Plot2svg is great. It would be even greater if it could automatically remove these parts of a plot that are masked (e.g. when limiting a plot in a subregion either with axis, xlim or ylim). This would create lighter svg plots and it would fix the problem of import svg files in some applications (e.g. scribus), as some of they take the whole area, including invisible parts, instead of what is the final visible figure. This makes the arrangement of different panels in a composed figure quite difficult.

I hope there is an easy way to do it. I definitely would appreciate it, and I guess other people too.

Thanks for your work!


This seems awesome but I'm having a problem with legends. The legend text strays outside of the legend box. Is there an easy fix for that? Try this to see what I mean:

>> figure
>> x = linspace(-pi, pi, 300);
>> plot(x,sin(x));
>> legend('A smooth curve');
>> plot2svg('sin.svg');



I recently stumbled over this and first of all, I love this package! It is truly brilliant and I especially like the WYSIWYGness of the exported SVGs.

However, this is also what I am having troubles with. I have had absolutely no problems with using plot2svg with ordinary plots. But today, I needed to use it for loglog and semilogx/semilogy plots and it does not work properly - or at least not in my opinion. I like to use "axis square" for my plots, as I like them to be square when I use them in my reports and papers. However, this creates problems when using plot2svg, especially for semilog plots, and the exported figures are squezzed together. Using "axis square" in Matlab yields a square plot, but it can have different scalings on the axes. It appears that when exporting using plot2svg, the scalings are somehow set to be equal instead of the plot dimensions being set to be equal. I would appreciate some help or a nudge in the right direction, as it is quite urgent.


The code

for ii=1:10
print 'testpc.eps' -depsc

produces different results on OS X and Windows.

In both cases, the eps file contains the fonts at the right sizes, i.e. 6,7,8,9,10,11,12,13,14,15 pt

In Windows the font sizes in the svg file are 6,7,8,8,9,10,11,12,13,14 (8 is repeated and every number above 8 is off by 1 point.)

In OS X the font sizes in the svg file are
8,9,10,11,12,14,15,16,18. All way off.

Stuart Layton

Great function! I use it often. I have one suggestion though, the length of the change log makes calling help on the file completely useless. To prevent the change log from showing up during a call to help add a single un-commented empty line between the copyright information and the changelog.

Shuhao Cao



There is a mysterious visible bounding box that shows up in the SVG file.

As an example, run:

color=[1 0 0]
hrect=annotation('rectangle',[0.3 0.5 .3 .2])

Note that the semi-transparent rectangle has no outline on screen, but it does in SVG.

To fix:
At the end of line 1787, immediately following the line:

if strcmp(linestyle,'none');

Shuhao Cao

Ben Mitch

hi Juerg - couple of other comments/questions...

(i) what does the "figuresize" argument do, it doesn't seem to be documented? exported size is controlled as described in "Plots for Scientific Publications", so what could "figuresize" be? am I not finding some documentation, perhaps?

(ii) re. "Plots for Scientific Publications", would it not be more consistent for the export size to be controlled by "PaperPosition"/"PaperUnits" rather than "Position"/"Units", since this is (as I understand it) what these "Paper..." properties are for? the way it is at the moment, the figure has to be updated on screen to affect the export size, which seems unnecessary.

great work :), cheers

Ben Mitch

hi Juerg. great contribution, thanks :)

"Benjamin" reported a bug in 2009 that appears to be still there. here is how to reproduce it:

set(gca, 'ytick', 0:10);


Index exceeds matrix dimensions.

Error in plot2svg>exponent2svg (line 2434)
ratio = numlabels(indexnz)./labelpos(indexnz);


I had a problem with exporting a figure:

Subscript indices must either be real positive integers or logicals.

Error in plot2svg>axchild2svg (line 1570)
patch2svg(fid, group, axpos, x(faces_nonan), y(faces_nonan),
facecolorname, linestyle, linewidth, edgecolorname, face_opacity,
edge_opacity, closed)

After investigation, the error is caused by patches with NaN faces. Removing NaN elements from the faces array fixed the problem. Here is the modification around line 1566:

faces_nonan = faces(p,:);
faces_nonan = faces_nonan(isfinite(faces_nonan));

if flat_shading
patch2svg(fid, group, axpos, x(faces_nonan), y(faces_nonan), facecolorname, linestyle, linewidth, edgecolorname, face_opacity, edge_opacity, closed)
gouraud_patch2svg(fid, group, axpos, x(faces_nonan), y(faces_nonan), cdata, linestyle, linewidth, edgecolorname, face_opacity, edge_opacity, id)

Thank you for this great library!



plot2svg is just great.

FYI, I think there is a bug when using scatter3 with different colors, as result from plot2svg appears with a single color.

Hope this can be fixed...


Using R212a on MacOS and I get the following error codes from the examples:

>> demo_3d_plot2svg
Matlab/Octave to SVG converter version 10-Nov-2010, Juerg Schwizer (
Error using fileparts
Too many output arguments.

Error in plot2svg (line 182)
[pathstr,name,ext,versn] = fileparts(finalname);

Error in demo_3d_plot2svg (line 14)


Slight bug at lines 1122 and 1131. Functions are missing variable projection.

Really nice! Thanks a lot for uploading this.

Murat Shagirov

Oliver Woodford

A fantastic piece of software that belies the complexity of this problem. It is the only way I know of exporting transparent vector objects from MATLAB. I often find myself recommending this function to people for that reason.

Ichinose Kamakura

Ichinose Kamakura


Thank you
Thank you
Love it!

Yuri K

Can I export IMAGESC plot without any blur? Like imagesc(rand(10))
Couldn't find a way yet.


Seems promising, although I have failed at the first hurdle. I receive the following error:

Error using fileparts
Too many output arguments.

Error in plot2svg (line 182)
[pathstr,name,ext,versn] = fileparts(finalname);

Error in demo_svg_water (line 76)

So, by typing:

The original graph appears but the it seems to fail when trying to use plot2svg.



Great tool! I use it to get around transparency (alpha) rendering issues for pdf. (Thx Jan Neggers for the tip on 2011b)


Kotya Karapetyan

Have I found a bug? When trying to plot2svg a brushed plot, I receive Error in plot2svg (line 221) ... Error in plot2svg>line2svg (line 2237) if parts(1)~=1: Attempted to access parts(1); index out of bounds because numel(parts)=0. Can anyone suggest a solution on how to export just one part of a curve? I need it for showing zoom-in's.


Thanks for sharing this. It's an important feature that should be standard in Matlab. As it is, I want to report that the suggested UTF-8 fix in the above notes is necessary for those of us using Matlab under Mac OS 10.7. Also, while I'm able to export surfaces, the camera position is not preserved.


arie meir

arie meir

Great tool !
Thanks again.


The following seems to fix the ylabel issue:

if get(ax, 'YLabel') == id

after x is computed in text2svg.


ylabels end up too close to the yticks on the axis in the SVG file. The Matlab figure is correct.

Jan Neggers

When using matlab2011b i get this:

Error in plot2svg (line 182)
[pathstr,name,ext,versn] = fileparts(finalname);

The solution is simple, just change line 182 to:
[pathstr,name,ext] = fileparts(finalname);

Anyway nice tool!

Vahid Bokharaie

I found the solution and mention it in here in case somebody else faces similar situation. The problem arose due to the fact that I uses:
axis([0 inf 0 10])
normally, Matlab interprets 'inf' in axis command as a hint to specify the upper bound of the axis itself, which is does and the plot is OK. But for some reason, plot2svg has an issue with that. Changing it to something like:
axis([0 5 0 10])
will fix the problem.

Vahid Bokharaie

It is very helpful, specially for somebody like me who wants to export figures to LaTex (through inkscape). I have successfully used plot2svg for a figure and it worked perfectly, however, for another figure, I got the following message:
Matlab/Octave to SVG converter version 10-Nov-2010, Juerg Schwizer (
Warning: The fourth output, VERSN, of FILEPARTS will be removed in a future release.
> In fileparts at 35
In plot2svg at 182
Warning: NaN found in Y, interpolation at undefined values
will result in undefined values.
> In interp1 at 179
In plot2svg>gridLines at 709
In plot2svg>axes2svg at 975
In plot2svg at 221

and the warning goes on and on for every 'gridline' following the first. And the output is almost empty. It is a 3x2 subplot with two titles, 6 ylabels and 2 xlabels.


Great work!
However there seams to be a problem when I try to export a plot where I used the command "axis square". In the SVG, the axis are completely squeezed horizontally...



Very useful for exporting high quality figures that use the fill function. Matlab really likes converting any figure that contains fill to raster, but this function exports them easily and adobe illustrator reads the files correctly.

Andrew Scott

This is really good.
One tiny point, on line 182:
[pathstr,name,ext,versn] = fileparts(finalname);
Needs 'versn' removing in 2011b.

Mr Smart


Great work on this excellent tool! I found a small bug though, which causes images to have two color channels flipped vertically. On line 1973 "for j = size(pointc,3)" should be changed to "for j = 1:size(pointc,3)".

Thomas Clark

I haven't used this really extensively, but I've just thrown a _very_ complex figure at it (coloured slice plots, multiple quivergroup objects, etc) and it handled the lot perfectly.

SO impressed, thanks Juerg!


Bug report, with a proposed fix:
Legend text "drifts" down and left in SVG's with repeated calls to plot2svg on the same plot. This also affects the plot in MATLAB when it gets redrawn (try maximize + restore on the window).

It is caused by converting the text units to 'Data' on line 2311. Converting between the 'Data' and 'normalized' units will cause the text position value to gradually change (this can be checked by comparing get(text_handle, 'Position') before and after repeated calls to set(text_handle, 'Units', 'data') and set(text_handle, 'Units', 'normalized')).

Proposed fix: keep track of the original position in addition to the original units:
@@ -2305,6 +2305,7 @@
function text2svg(fid,group,axpos,paperpos,id,ax,projection)
global PLOT2SVG_globals;
+originalTextPosition = get(id, 'Position');
if PLOT2SVG_globals.octave
@@ -2363,6 +2364,7 @@
+set(id,'Position', originalTextPosition);

Nik F

Not /perfect/, but pretty amazing for what it does!

Kotya Karapetyan

Plot setting command

xlabel('Wavelength, nm', 'FontUnits', 'normalized', 'FontSize', 0.03);

causes plot2svg to crush with

??? Error using ==> plot2svg>convertunit at 2804
Unknown unit normalized.


Bug report:
When there are more than one line in the x or y label they will be written on top of each other. It creates the two lines as different text objects so the error can be corrected through inkscape.

The plot looks fine in matlab using this command:
xlabel({'this is line one', 'and line 2'})

Tommy Sebastian

Highly useful code! One small problem, however... for 3d plots, colors do not seem to come up correctly. Using RGB to define a green surface [0 1 0] results in a green surface in the figure, but a blue surface for the svg image... similar problems for other colors as well. Suggestions?

Frederic Roux

same problem as Yohai. pcolor plot has white mesh/grid overlaid on top. how can i get rid of it?

Tsz Ho Yu

An excellent solution for generating transparent patches in Matlab!

Yet, I found that the legend are not rendered in my SVG files. Once I guess it is because the legends are plotted outside the axes, but there is no legend rendered in my plots even I put them back inside the plots...

Matthias Pospiech

I found that your code works well and provides results that match very well the wanted linestyles and fonts specified. However the plot is cropped at the upper boundary which should not happen.
I have posted an example of this here:

It would be great if this could be improved.


This does sound like a great tool, but on matlab R2009a in linux, the example demos (tutorial and svg_water) do not run successfully. They both fail to embed the background figures.


Small bug report.
My plots have an axis label coded by:
ylabel('Oscillator Strength (eV^{-1})')
but the svg file is missing the final ')'.

This is a great piece of code, well done!

Juerg Schwizer

Dear Catarina,

Many thanks for your feedback. Unfortunately, plot2svg has at the moment no support for depth sorting of graphics objects. Only depth sorting of surfaces is supported. To support an universal dept-sorting I have to design a z-buffer algorithm from scratch or use a c++/java library. Or I would need access to the Matlab internals. At the moment, my plot2svg has to generate the svg elements just from the user data. Also the svg element saving has to be changed as I need some further buffering and sorting before writing the svg file. Thus, it would be a major change.
For your application, you have to split the line into two parts and sort the elements according their z-position in the view space. There are some code fragments in the plot2svg code that do the same thing for surfaces.
I'm sorry that I can give you no better advice at the moment. Let's hope that the Matlab graphics engine itself gets some upgrading with improved support of all the new technologies like svg, filters, animation, ...

Catarina Avelino

I found this tool great except for one thing that for me is not working. If we consider the code:

function exp
[X,Y,Z] = sphere(30);
mesh(X,Y,Z,'facecolor',[0.7 0.7 0.7],'edgecolor','none'); hold on;
A = [0,0,1]';
B = [1,0,0]';
v3 = cross(cross(A,B),A);
t = linspace(0,atan2(norm(cross(A,B)),dot(A,B)));
v = A*cos(t)+v3*sin(t);
view([80, -40])
axis equal, hidden off,
hold off
axis off

we see a sphere with a line drawn where one part lies in front of the sphere and another part lies behind the sphere (the figure has transparency). In the matlab figure there is disctintion of those two different parts on the line colors. In the svg file we saw that there is no distinction of colors, i.e., the color of the line is the same whatever the line is ahead or behind the sphere.

There is a way to create the svg file with different colors for the objects created in front and behind the sphere? Or to make the lines behind dotted?

I would appreciate your help!

Eric Tittley


Works great for simple plots.
However, it doesn't work for pcolor. It creates a big file (11M) which doesn't look like the figure I've created.
Can it be a Linux-compatability problem?

Jonathon Harding

This is working excellently for me! I can finally output graphs in vector format with fonts other than Helvetica.

One minor bug report: (La)TeX strings that end with a single character after the last curly brace will drop that character (e.g. a_{sub}b would only display a_{sub}).

This can be fixed by changing line 2613 to:
if lastValidCharacter <= length(StringText)
The important part is the less than or equals, rather than a strict less than.


By far one of the most useful pieces of code I've come across. I used to trace Bezier curves on top of .png images *by hand* in a vector graphics editor to get .svg images for papers and posters. I can't even begin to describe how much time/frustration this will save me! Thanks so much!


Thank you! I was constantly adjusting figures in Inkscape that did not copy properly from Matlab. Problem soved!

Patrick Mineault

Bug report:

I ran into trouble when attempting to use ImageMagick's convert command line program with an svg generated by plot2svg (e.g convert myplot.svg myplot.png). The aspect ratio of the output was way off. However when I loaded the same file in Illustrator it came out fine. Comparing Illustrator and plot2svg output, I found the following solution:

Replace line 176 with:

fprintf(fid,'<svg preserveAspectRatio="xMinYMin meet" width="%0.3fpx" height="%0.3fpx" viewBox="0 0 %0.3f %0.3f" ',paperpos(3),paperpos(4),paperpos(3),paperpos(4));

As an added bonus, I now get correct crop marks when I load the file in Illustrator.

Patrick Mineault

It didn't work immediately with a figure with a /patch/ (the outlines were correct but the colors didn't show up). Got it to work by switching to the /fill/ command instead. The output is exceedingly accurate compared with the eps exporters based on the painters renderer which tries to simplify/merge outlines and messes up a lot of small details. Excellent work!

Patrick Mineault


Gladnon Galoshev

Juerg Schwizer

% Example how to adjust your figure properties for
% publication needs (answer to Aslak Grinsted's question)
s = figure;
% Select the default font and font size
% Note: Matlab does internally round the font size
% to decimal pt values
set(s, 'DefaultTextFontSize', 10); % [pt]
set(s, 'DefaultAxesFontSize', 10); % [pt]
set(s, 'DefaultAxesFontName', 'Times New Roman');
set(s, 'DefaultTextFontName', 'Times New Roman');
% Select the preferred unit like inches, centimeters,
% or pixels
set(s, 'Units', 'centimeters');
pos = get(s, 'Position');
pos(3) = 8; % Select the width of the figure in [cm]
pos(4) = 6; % Select the height of the figure in [cm]
set(s, 'Position', pos);
set(s, 'PaperType', 'a4letter');
% From SVG 1.1. Specification:
% "1pt" equals "1.25px"
% "1pc" equals "15px"
% "1mm" would be "3.543307px"
% "1cm" equals "35.43307px"
% "1in" equals "90px"


Really great! Thanks a lot!

just one small problem with log scaled axes. To reproduce:
figure; plot(0:5, 0:5);
set(gca, 'xLim', [0 5]);
set(gca, 'xScale', 'log');

Solution: always set lower xLim > 0, if you use log scaled axes.
(I know: quite obvious! :-) ...but this case could simply come true)

I guess this exception could be trapped in function get_projection (around line 1913): if xi(1) == Inf ...

Juerg Schwizer

Hi Felix, many thanks for the feedback! Bug 1 is already implemented together with additional tex elements. These changes will soon be published together with a minor label bugfix. I was not able to reproduce bug 2 & 3. Could you please send me an example. Many thanks. Juerg.

Felix Zoergiebel

Yet another bug when plotting the y-axis on the right side of the plot-box: label positions are inverted, i.e. labels are not [1 2 3 4 5] but [5 4 3 2 1] (data is still plotted as in figure)

Felix Zoergiebel

Great job! This really helps me plotting translucent patches, which is just not possible with matlab functions. However, there are small problems.
1: latex \cdot is not processed. I added
tex=strrep(tex,'\cdot','& # 8901;'); (without spaces...)
to line 2351 of plot2svg_beta.m
2: I have an hggroup with text objects that are placed outside of the axis (custom labels). These labels are not plotted before I set the parent of each of them to the axis.


Great, too bad LaTeX-interpreted text() results are not interpreted...and {} don't help, I get $v$ or {$v$} in the SVG file ... :'(

Aslak Grinsted

I would like to use plot2svg for producing figures for publications. (I am often having problems with matlabs print when there is anything transparent in the plot.)

That means i would like to use absolute units for the size. I would also like to specify the font size, linewidth in units of points. Many journals have strict requirements on these.

Rob Campbell

I love it! I see I shall be using this a lot.
Seems to work very well in Firefox (all I've tried so far).
Am about to use it for generating HTML reports of analyses.


without this presenting results would suck!

in order to ensure utf 8 encoding, change two lines in plot2svg.m
142: fid=fopen(finalname,'wt', 'n', 'UTF-8'); % Create a new text file
143: fprintf(fid,'<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "">\n'); % Insert file header

Eddie Seven

yay, it works. I wrap a rsvg-convert after it to get a png file. even for simple plots, it's scandalous how bad the matlab internal plot saving utilities are.

Kristin B.


Juerg Schwizer

Hi Cesar Roda Neve,
This is not a bug in plot2svg. It's a limitation of Inkscape and Firefox. Other browsers like Opera or Chrome can handle it. The SVG code for sub and super script is conform to the SVG 1.1 specification. I'm aware of the limitation and will try to find a workaround for Inkscape and Firefox.

Cesar Roda Neve

I have found a bug. When i write in the axis label a text including super or sub script, just something like:


It just ignore the super or sub thing and write it together...


It should be nice if someone has an idea of how to fix this.


very usefull tool
It would be nice if someone could compile the bug fixes listed above and release a updated version... (probl. Juerg is already working on that...?)


Bug report:
If I set ytick manually, but then also set ylim so that not all yticks are displayed, then I get an "Index exceeds matrix dimensions" error.

line 1019 of plot2svg_2d:

indexnz=find(labelpos ~= 0)

should be changed to:

indexnz=find(labelpos ~= 0 & labelpos >= labellimit(1) & labelpos <= labellimit(2))

and obviously, line 1003 should be changed similarly for the x-axis case.

Ritesh Sood

found a little bug on line 823 of plot2svg_2d.m which was causing firefox to hit a parsing error. The original line code is
case '-.',pattern = 'stroke-dasharray="100pt,25pt,25pt,25pt,"';
which should be changed to
case '-.',pattern = 'stroke-dasharray="100pt,25pt,25pt,25pt"';
(The bug is the trailing `," after the last 25pt.)
There are a few issues that I'm seeing in the exported svg:
1) subscripted labels like "f(t_1,t_2)" are appearing verbatim; subscripts are not getting interpreted as I believe they should.
2) I have a figure with two 2D contour plots differentiated by one set of contours being solid and the other set dot-dashed. The svg output is unfortunately quite poor: one can hardly make out that there are two sets of contours.
For (1) above I have an idea: SVG+MathML
I am using MathML to render a table of parameters -- which requires some math typesetting, greek symbols, matrices -- to go along with the plots. The way I am doing that is to have tex (well, itex actually) markup in the file and pass the file through itex2MML.
Maybe the same process will work with the svg figures. Enclose the math in the labels in a pair of
`$"s (requited by itex), set Matlab's Interpreter to Latex so that the fig file comes out alright, create an svg and filter through itex2MML. Let's see how that goes.
If only Matlab had native SVG support, wouldn't have to jum through all these hoops...

Georg Stillfried

The advice by Sebastien Besson did the trick. Thanks!


Mike Schachter

Sorry, kind of screwed up there - what I was trying to do was plot a handle that comes from a call to the polar(...) command. plot2svg works fine for figure handles. I retract my fix, but not the whole dying-without-plot2svg thing.

Mike Schachter

By the way, this is the most awesome and necessary script I've ever used. When it stopped working I wanted to die and thought the world around me was crumbling to pieces, leaving me shattered and vulnerable to the cruel biddings of Adobe Illustrator.

But now those days are over, I can breathe a breath of joy knowing that I can continue to use Inkscape for making figures! Hurrah!

Mike Schachter

Just to be specific, you can paste that code at line 40 of plot2svg_2d.m.

Mike Schachter

plot2svg doesn't work for higher MATLAB versions (such as 7.6), but here is a fix. Put this near the top of plot2svg_2d in order to make things work:

if (str2num(matversion(1)) >= 7)
disp(' Using grandparent id due to higher matlab version.');
id = get( get(id, 'Parent'), 'Parent');

Sebastien Besson

Hi Georg,

I experienced the same problem and solved it by replacing lines 1121 and 1130 :
group=axchild2svg(fid,id,axIdString,ax,group,paperpos,get(axchild(i), 'Children'),axpos,groupax);
group=axchild2svg(fid,id,axIdString,ax,group,paperpos,get(axchild(i), 'Children'),axpos,groupax,projection);

Hope it will help you.

Georg Stillfried

unfortunately I recieve an error when I try to export patch and surface objects (Matlab 7 on Linux)

>> plot2svg('figure.svg')
Matlab to SVG converter version 22-Jan-2006, Juerg Schwizer (
??? Input argument "projection" is undefined.

Error in ==> plot2svg>axchild2svg at 902
[x,y,z] = project(points(1,:),points(2,:),points(3,:),projection);

902 [x,y,z] = project(points(1,:),points(2,:),points(3,:),projection);

Georg Stillfried

very nice, works well

george melinkus

How long will it take The Mathworks to include this functionality in Matlab by default?! It has been asked multiple times and would be a BIG plus considering the growing support for the format, both closed and open source.

Just wondering... big thumbs up for the author of this export script!

Mazen Saied


Great work and congratulations for this macro. I have found a bug to correct. It concerns surface intersections when you plot 2 or more surfaces (surf, mesh, ...). I notices that when you export in SVG format, plotted surfaces are stacked one on the other and their intersections disappear.

Nevertheless, all the rest is perfect.
Thank you

sylvain lalure

Dmitry Babin

A correction to my previous post (from 2008-05-15):

1. LaTeX commands ARE interpreted, but only when enclosed by curly braces. For example:
xlabel('\bft\rm, [sec]')
isn't interpreted correctly;
xlabel('{\bft}, [sec]')
is OK.

2. About "surf" and "mesh" plots: my mistake... I tried to use it in this way:
h = surf(.........)
The correct way to get a handle is:
h = figure(1)

Mat Hunt

Interoperability with octave would also be a good idea, I get the error message (with octave):
Matlab to SVG converter version 22-Jan-2006, Juerg Schwizer (converter@juergs
Warning: Future versions may no more support older versions than MATLAB R12.
error: `uiputfile' undefined near line 52 column 29
error: evaluating if command near line 51, column 1
error: called from `plot2svg' in file `/home/mat/plot2svg.m'

Dmitry Babin

Bug report (MATLAB R2008a, not tested with older versions):
1. LaTeX commands are not interpreted (e.g. \bf appears in SVG text strings)
2. When trying to use it with surf plots, the following error message appears:

??? Error using ==> get
There is no 'Units' property in the 'surfaceplot' class.

Error in ==> plot2svg at 87

nino guttuso

Jason Merrill

This is fantastic. I think this may allow me to dump Illustrator in favor of Inkscape. One cross-platform thing: on Unix/Mac, files always get saved with an extra backslash in front of them. A quick fix is to replace the explicit string '/' with filesep in the addBackSlash subfunction (lines 1652-1653 in plot2svg, and lines 1232-1233 in plot2svg_2d). Here's the corrected version:

function strString=addBackSlash( strSlash)
% adds a backslash at the last position of the string (if not already there)
if ( strSlash(end) ~= filesep)
strString = [ strSlash filesep];
strString = strSlash;

I suspect this could all be cleaned up (i.e. you wouldn't even need the addBackSlash function) using the fullfile function.

r. h.

Bug report. Used without arguments.

??? Attempted to access cdata(2,:); index out of bounds because size(cdata)=[1,21].

Error in ==> plot2svg>gouraud_patch2svg at 1208
face_color2 = cdata(j-1,:);

Error in ==> plot2svg>axchild2svg at 861
gouraud_patch2svg(fid, group, axpos, x(faces(p,:)), y(faces(p,:)),
cdata, linestyle, linewidth, edgecolorname, face_opacity,

Error in ==> plot2svg>axes2svg at 459
group =

Error in ==> plot2svg at 139

Kaushik Ghose

This is a great script! Thank you for making it.
I use inkscape to edit the svg files and I find the following issues:

1. I need to hand code the font into the file (i.e. I need to force
textfontname = 'Arial';

2. I need to remove the "pt" from all the font size descriptions


Sam R

This is excellent. Matlab allows you to save figures in illustrator's format, but it does not handle transparency of 3D planes. This script does and makes it possible to have a vectorial file of 3D surfaces with transparency. Thanks!

Geoff Adams

Very nice function. However, I believe I have found a bug. On line 1121, "axchild2svg" is called without the "projection" argument. Adding it in seems to fix the problem. So to fix the bug:

--At line 1121, replace:
group=axchild2svg(fid,id,axIdString,ax,group,paperpos,get(axchild(i), 'Children'),axpos,groupax);
group=axchild2svg(fid,id,axIdString,ax,group,paperpos,get(axchild(i), 'Children'),axpos,groupax,projection);

Jarek Tuszynski

Great tool.

Frouke H

I got the following error message:
"??? Attempted to access xg_label_end(5); index out of bounds because numel(xg_label_end)=4.

Error in ==> plot2svg>axes2svg at 545

Error in ==> plot2svg at 139

What do I do wrong?

jhgjh ouyou

Stijn Klaassen

Great tool for exporting graphs to Inkscape!
Get an error when making a plot using errorbar:
"??? Input argument "projection" is undefined.Error in ==> plot2svg>axchild2svg at 706 [x,y,z] = project(linex,liney,linez,projection);
Error in ==> plot2svg>axchild2svg at 1121 group=axchild2svg(fid,id,axIdString,ax,group,paperpos,get(axchild(i), 'Children'),axpos,groupax);
Error in ==> plot2svg>axes2svg at 459
group = axchild2svg(fid,id,axIdString,ax,group,paperpos,axchild,axpos,groupax,projection);
Error in ==> plot2svg at 139 group=axes2svg(fid,id,ax(j),group,paperpos);"

Anybody an idea for a workaround?

bassam atallah

Great little application. It is helpful. A few comments.
Doesn't seem to deal correctly with:
1) When background axis 'Color' is set to 'none' (you get a none white background)
2) Doesn't support histogram plots in the form of 'bar' or 'stairs'


Great job,It is very interesting
Thank for good experience
From thailand

bahram houchmandzadeh

Great work. For must stuff we do, matlab plots are not that sophisticated and the package just works.

Jean-Francois Dupuis

To handle bar plot, just use the backward compatibility flag such as : bar('v6', ...);

J. V.


I don't see why doesn't Matlab have an "export to SVG" option yet. Juerg Schwizer did a great job, but it is too much for a single person to implement the full support for SVG.

It works ok for simple graphics. But it fails with transparencies and flat FaceColor. Take the example in the documentation for the "patch" command

vert = [0 1 1;0 2 1;1 2 1;1 1 1];
fac = [1 2 3;1 3 4];
tcolor = [1 1 1;.7 .7 .7];

plot2svg 'matlab_patch_example.svg'

bass atallah

Works well for the most part. Gives an error and doesn't converst bar graphs though.

phox hat

Just what I needed!

Benjamin Watts

Excellent function, I will use this alot!

Bug: setting XTick with any numbers outside of the set xlim in the figure will cause an error in plot2svg.

S. Barth

Great! Spent too much time to find something comparable.

Monsieur Truc

Thanks, this is great and should be implemented natively in Matlab.
Tip : if you want smaller files, convert the multilines objects (curves...) into pathes with inkscape and use the 'simplify' tool.

Timothy Withheld

this piece of code is amazing. the svg exports work perfect with inkscape which is _exactly_ what i needed.

Kris De Gussem

Should be part of Matlab itself

m m

Get confused if you manually alter the axis scales: e.g. Inkscape still reports layers of the 'original' size I think. Also non-size preserving in pixels at the least. Needs specifically size setting in e.g. Inkscape before external users will recognise the pixel size settings. Otherwise, very goodl

Yordan Kyosev

Thank you Juerg!

E Dinnat

Just tried the 3D functionality on a few samples. Works great. Excellent and very usefull function. Too bad light is not exported and interpolated shading is not excellent, but I guess that SVG (or any vector format) isn't suited for so complex rendering.

Ken Senior

Running the plot2svg command on my Windows XP R14SP3 gives the error:
??? Error: File: plot2svg.m Line: 1763 Column: 1
The function "get_projection" was closed
with an 'end', but at least one other function definition was not.
To avoid confusion when using nested functions,
it is illegal to use both conventions in the same file.

Wladimir van der Laan

You just saved my day :-) I tried so many things, like exporting .ai and trying to import it in inkscape, but it all yielded corrupted plots or nothing at all. With this program, it works perfectly.

Matthias Schabel

Very nice work. Default plot size appears quite small when imported into Illustrator - 400% magnification required to make image fit standard page. Otherwise great help for preparing plots for publication.

Charlie Eckelston

Great tool for editing plots for publications

tom mod

Heiko Marx

Nice! What I first found was that for zoomed plots the data exceeds the plot area. And the files become quite large. And having lots of controls causes having lots of jpegs. But because we use the .svg-format very often, this is a very useful tool with a lot of potential! Thank you!

MATLAB Release Compatibility
Created with R2012b
Compatible with any release to R2014a
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!