File Exchange

## Scalable Vector Graphics (SVG) Export of Figures

version 1.8 (839 KB) by

Converts 3D and 2D MATLAB plots to the scalable vector format (SVG).

4.52941
137 Ratings

Updated

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 (http://www.w3.org) 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. More information and examples can be found on my blog http://www.zhinst.com/blogs/schwizer/.

Tested browsers and editors for basic SVG support (no filters, no animation):
Opera 9.64,10.50,10.63 -> yes
Firefox 3.5,3.6,12.0 -> yes
Inkscape 0.46, 0.47 -> yes
Chrome 8.0,18.0 beta -> yes
Internet Explorer 9.0 beta -> yes
Internet Explorer 8.0 -> no
Internet Explorer + RENESIS -> yes

Tested browsers and editors for SVG filters:
Opera 9.64,10.50,10.63 -> yes
Firefox 3.5,3.6,12.0 -> yes
Inkscape 0.46, 0.47 -> yes (some limitations)
Chrome 8.0,18.0 beta -> yes
Internet Explorer 8.0, 9.0 beta -> no
Internet Explorer + RENESIS -> no

Editors for the SVG file format can be found at http://www.inkscape.org.

Usage:
> plot2svg % opens a file dialog to plot the active figure
or
> 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>

Changes in Version 10-11-2010
- Support of the 'Layer' keyword to but the grid on top of
of the other axis content using 'top' (Many thanks to Justin
Ashmall)
- Tiny optimization of the grid display at axis borders

Changes in Version 25-08-2011
- Fix for degree character (thanks to Manes Recheis)
- Fix for problems with dash-arrays in Inkscape (thanks to
Rüdiger Stirnberg)
- Modified shape of triangles (thanks to Rüdiger Stirnberg)

Changes in Version 22-10-2011
- Removed versn as return value of function fileparts (thanks
to Andrew Scott)
- Fix for images (thanks to Roeland)

Changes in Version 20-05-2012
- Added some security checks for empty data
- Fixed rotation for multiline text

- Special handling of 1xn char arrays for tick labels
(thanks to David Plavcan)
- Fix for 'Index exceeds matrix dimensions' of axis labels
(thanks to Aslak Grinsted)
- Fix for another axis label problem (thanks to Ben Mitch)

Changes in Version 15-09-2012
- Fix for linestyle none of rectangles (thanks to Andrew)
- Enabled scatter plot functionality

Limitations:
- axis scaling factors for 3D axes
- 3D plot functionality limited (depth sorting, light)

Example of a SVG file is included to the zip file.

Reports of bugs highly welcome.

Yair Altman

### Yair Altman (view profile)

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

Yair Altman

### Yair Altman (view profile)

@Martin - the version of plot2svg on the Matlab File Exchange is relatively old (2012) compared to the latest one on Github (<a href="https://github.com/jschwizer99/plot2svg -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: https://undocumentedmatlab.com/blog/customizing-axes-tick-labels#comment-418789

Martin Dawson

### Martin Dawson (view profile)

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

### Frantisek Pernis (view profile)

Warning: Unhandled child type: implicitfunctionline

Avisha NessAiver

### Avisha NessAiver (view profile)

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

### Mark T (view profile)

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

### Dominik Puckert (view profile)

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)
exponent2svg(fid,groupax,axpos,paperpos,ax,axxtick,axytick,axztick)

Error in plot2svg (line 243)
group=axes2svg(fid,id,ax(j),group,paperpos);

Error in demo_svg_water (line 76)
plot2svg('demo_svg_water.svg')

Will Lykins

### Will Lykins (view profile)

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)
exponent2svg(fid,groupax,axpos,paperpos,ax,axxtick,axytick,axztick)

Error in plot2svg (line 243)
group=axes2svg(fid,id,ax(j),group,paperpos);

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

### Manjunath Navalgund (view profile)

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

### Victor Yashunsky (view profile)

Keep getting the following message
"Warning: Unhandled child type: quiver"

Jon Matthis

### Jon Matthis (view profile)

I get the following error, any advice?

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

Matlab/Octave to SVG converter version 15-Sep-2012, Juerg Schwizer (converter@bluewin.ch).

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)
exponent2svg(fid,groupax,axpos,paperpos,ax,axxtick,axytick,axztick)

Error in plot2svg (line 243)
group=axes2svg(fid,id,ax(j),group,paperpos);

Sebastian

Justin Baik

### Justin Baik (view profile)

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

Amaizing

Milz Dag

### Milz Dag (view profile)

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

### Sandor Toth (view profile)

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

### Tomas Zegard (view profile)

--- 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)
group=axes2svg(fid,id,ax(j),group,paperpos);

--- To solve, replace lines 1588-1590 with the following kludge:
try
patch2svg(fid, group, axpos, x(faces(p,:)), y(faces(p,:)), facecolorname, linestyle, linewidth, edgecolorname, face_opacity, edge_opacity, closed)
catch
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)
end
else

Sharah

### Sharah (view profile)

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

otherwise would be a good function

Yupeng li

Thomas Fastl

### Thomas Fastl (view profile)

Hey,

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!

/Tom

Karsten Kuhlmann

### Karsten Kuhlmann (view profile)

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.

Tobias

### Tobias (view profile)

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.

Tobias

### Tobias (view profile)

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.

RAHUL

### RAHUL (view profile)

You are a life saver. Thank you so much !

will wehner

### will wehner (view profile)

How can this be used for animations?

Peter Griffin

### Peter Griffin (view profile)

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.

### Muhammad Wasim Akhtar Khan (view profile)

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

### Paul Macey (view profile)

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:
BEFORE
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});
end
else
numlabels = str2num(get(ax,'YTickLabel'));
end

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

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
* 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.

keleca

### keleca (view profile)

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 ?

FranticFrog

### FranticFrog (view profile)

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

### Vincent Prevosto (view profile)

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);

Marcel Beining

### Marcel Beining (view profile)

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

### Felipe BM (view profile)

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!

G.

### G. (view profile)

In Matlab 2014b:

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

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

Carl Wouters

### Carl Wouters (view profile)

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.

John

### John (view profile)

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

CarstenChaos

### CarstenChaos (view profile)

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

### Durga Lal Shrestha (view profile)

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

Juerg Schwizer

### Juerg Schwizer (view profile)

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

https://github.com/jschwizer99/plot2svg

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

Valentin

### Valentin (view profile)

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];
end
end
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];
end
%end
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.

NGUYEN

### NGUYEN (view profile)

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)
[z,face_index]=sort(sum(z(faces(:,:)),2));

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

Error in plot2svg (line 243)
group=axes2svg(fid,id,ax(j),group,paperpos);

Thanks a lot

Rodolphe

### Rodolphe (view profile)

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

Neil Dalchau

### Neil Dalchau (view profile)

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')
plot2svg('test.svg')

Bauyrzhan Aubakir

Richard

### Richard (view profile)

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.

Richard

Mirko

### Mirko (view profile)

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

Mirko

### Mirko (view profile)

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 =
str2num(get(ax,'XTickLabel'));

Error in plot2svg>axes2svg (line 1321)
exponent2svg(fid,groupax,axpos,paperpos,ax,axxtick,axytick,axztick)

Error in plot2svg (line 243)
group=axes2svg(fid,id,ax(j),group,paperpos);

Darik

Jeff

### Jeff (view profile)

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});
to
numlabels(ix) = str2double(axlabely{ix});

Otherwise, it does just what I need, thanks!

Ehsan

### Ehsan (view profile)

• 1 file
• 4.93333

One of my favorites. Thank you

xiaomi

### xiaomi (view profile)

I tried your code, and it works for me.

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

Durga Lal Shrestha

### Durga Lal Shrestha (view profile)

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

### Alessandro Masullo (view profile)

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

It can be easly reproduced by:

scatter(rand(1,10),rand(1,10),30,rand(1,10),'s','filled')
plot2svg('test.svg')

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

Natan

### Natan (view profile)

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

Sinan Teske

### Sinan Teske (view profile)

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)];

to

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)];

under line
elseif strcmp(get(axchild(i),'Type'),'patch')

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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!!

### Adam Andersen Læssøe (view profile)

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

Giorgio

### Giorgio (view profile)

I was looking for something like this for weeks

Sebastian Hölz

### Sebastian Hölz (view profile)

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.

ejs

### ejs (view profile)

Hi ANI,

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

Richi

### Richi (view profile)

This has saved me days in exporting MATLAB figures!

ANI

### ANI (view profile)

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;
openfig(fileName);
plot2svg('fileName.svg');
end

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?

ejs

### ejs (view profile)

Hi All,

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

Matlab/Octave to SVG converter version 15-Sep-2012, Juerg Schwizer (converter@bluewin.ch).
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
Error in plot2svg>axchild2svg (line 2075)
group=axchild2svg(fid,id,axIdString,ax,group,paperpos,get(axchild(i),
'Children'),axpos,groupax,projection,boundingBoxAxes);

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

Error in plot2svg (line 243)
group=axes2svg(fid,id,ax(j),group,paperpos);

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;
linex=log10(linex);
end

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

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

Hope it will not negatively affect the entire code ;)

Mike

### Mike (view profile)

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

Emmanuel Farhi

### Emmanuel Farhi (view profile)

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

Noah Levine-Small

### Noah Levine-Small (view profile)

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

### Jeroen Oomkes (view profile)

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

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

Pearl

Bharath Lohray

### Bharath Lohray (view profile)

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: http://img801.imageshack.us/img801/4204/crmm.png
http://pastebin.com/UsmAbSay - The generated svg

Chuntao Dan

### Chuntao Dan (view profile)

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

### Nam Tran (view profile)

Hi,
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 ?

loich

### loich (view profile)

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

### Greg Hale (view profile)

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

avlas

### avlas (view profile)

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.

Dominique

### Dominique (view profile)

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');

Thanks!

Joe

### Joe (view profile)

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.

Alan

### Alan (view profile)

The code

figure
for ii=1:10
h(ii)=text(0,ii/10,'QWERTYUIOPqwertyuiop1234567890');
set(h(ii),'fontname','courier')
set(h(ii),'fontsize',(ii)+5);
end
print 'testpc.eps' -depsc
plot2svg('test.svg')

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

### Stuart Layton (view profile)

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

Andrew

### Andrew (view profile)

BUGFIX & PATCH

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

As an example, run:

figure;
axes
alpha=.2
color=[1 0 0]
hrect=annotation('rectangle',[0.3 0.5 .3 .2])
set(hrect,'FaceColor',color);
set(hrect,'FaceAlpha',alpha);
set(hrect,'LineStyle','none');
plot2svg('test.svg')

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:
scolorname=searchcolor(id,get(axchild(i),'EdgeColor'));

INSERT:
linestyle=get(axchild(i),'LineStyle');
if strcmp(linestyle,'none');
scolorname='none';
end

Shuhao Cao

Ben Mitch

### Ben Mitch (view profile)

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

### Ben Mitch (view profile)

hi Juerg. great contribution, thanks :)

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

figure(1)
plot(randn(100,1));
set(gca, 'ytick', 0:10);
plot2svg

--------

Index exceeds matrix dimensions.

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

Philippe

### Philippe (view profile)

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));

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

Thank you for this great library!

avlas

### avlas (view profile)

Hi,

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...

Andre

### Andre (view profile)

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 (converter@bluewin.ch).
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)
plot2svg('sphere.svg');

Aaron

### Aaron (view profile)

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

German Gomez-Herrero

Murat Shagirov

Oliver Woodford

### Oliver Woodford (view profile)

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 (view profile)

Ichinose Kamakura

chao

Thank you
Thank you
Love it!

Yuri K

### Yuri K (view profile)

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

Richard

### Richard (view profile)

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)
plot2svg('demo_svg_water.svg')

So, by typing:
plot2svg('demo_svg_water.svg')

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

Il

Il

### Il (view profile)

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

Il

Kotya Karapetyan

### Kotya Karapetyan (view profile)

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.

Steven

### Steven (view profile)

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.

Steven

arie meir

arie meir

Great tool !
Thanks again.
A.

Petter

### Petter (view profile)

The following seems to fix the ylabel issue:

if get(ax, 'YLabel') == id
x=fontsize*1.25*1.2;
end

after x is computed in text2svg.

Petter

### Petter (view profile)

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

Jan Neggers

### Jan Neggers (view profile)

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

### Vahid Bokharaie (view profile)

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

### Vahid Bokharaie (view profile)

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 (converter@bluewin.ch).
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.

Alexandre

### Alexandre (view profile)

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...

Sébastien

Christian

### Christian (view profile)

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

### Andrew Scott (view profile)

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

Mr Smart

Roeland

### Roeland (view profile)

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

### Thomas Clark (view profile)

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!

Jonathon

### Jonathon (view profile)

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;
originalTextUnits=get(id,'Units');
+originalTextPosition = get(id, 'Position');
if PLOT2SVG_globals.octave
set(id,'Units','data');
else
@@ -2363,6 +2364,7 @@
label2svg(fid,group,axpos,id,x,y,'',textalign,textrot,textvalign,lines,paperpos,font_color,0)
end
set(id,'Units',originalTextUnits);
+set(id,'Position', originalTextPosition);

Nik F

### Nik F (view profile)

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

Kotya Karapetyan

### Kotya Karapetyan (view profile)

BUG REPORT:
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.

Jacob

### Jacob (view profile)

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

### Tommy Sebastian (view profile)

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

### Frederic Roux (view profile)

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

Tsz Ho Yu

### Tsz Ho Yu (view profile)

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

### Matthias Pospiech (view profile)

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:
http://www.matthiaspospiech.de/blog/2010/10/11/matlab-figures-solving-export-problems/3/#toc-plot2svg

It would be great if this could be improved.

Carlos

### Carlos (view profile)

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.

Benjamin

### Benjamin (view profile)

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!
Thanks,
Ben

Juerg Schwizer

### Juerg Schwizer (view profile)

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, ...
Juerg

Catarina Avelino

### Catarina Avelino (view profile)

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

function exp
set(gcf,'Color',[0.95,0.95,0.95])
[X,Y,Z] = sphere(30);
mesh(X,Y,Z,'facecolor',[0.7 0.7 0.7],'edgecolor','none'); hold on;
alpha(.7);
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);
plot3(v(1,:),v(2,:),v(3,:),'LineWidth',0.2,'Color',[0.3,0.3,0.3])
view([80, -40])
axis equal, hidden off,
hold off
axis off
plot2svg('exp.svg')
end

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?

Catarina

Eric Tittley

Yohai

### Yohai (view profile)

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

### Jonathon Harding (view profile)

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.

Brock

### Brock (view profile)

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!

Ryan

### Ryan (view profile)

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

Patrick Mineault

### Patrick Mineault (view profile)

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

### Patrick Mineault (view profile)

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

Rahul

Juerg Schwizer

### Juerg Schwizer (view profile)

% 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"

Juergen

### Juergen (view profile)

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');
plot2svg

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

### Juerg Schwizer (view profile)

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

### Felix Zoergiebel (view profile)

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

### Felix Zoergiebel (view profile)

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.

Zboud

### Zboud (view profile)

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

### Aslak Grinsted (view profile)

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

### Rob Campbell (view profile)

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.

me

### me (view profile)

great!
without this presenting results would suck!

btw.
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" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n'); % Insert file header

Eddie Seven

### Eddie Seven (view profile)

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.

T

Juerg Schwizer

### Juerg Schwizer (view profile)

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

### Cesar Roda Neve (view profile)

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

Text_{Material}

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

TextMaterial

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

Vincent

### Vincent (view profile)

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...?)

Benjamin

### Benjamin (view profile)

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.

Fix:
line 1019 of plot2svg_2d:

indexnz=find(labelpos ~= 0)

should be changed to:

labellimit=get(ax,'YLim')
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

### Ritesh Sood (view profile)

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

### Georg Stillfried (view profile)

The advice by Sebastien Besson did the trick. Thanks!

Florian

Mike Schachter

### Mike Schachter (view profile)

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

### Mike Schachter (view profile)

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

### Mike Schachter (view profile)

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

Mike Schachter

### Mike Schachter (view profile)

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');
end

Sebastien Besson

### Sebastien Besson (view profile)

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);
by
group=axchild2svg(fid,id,axIdString,ax,group,paperpos,get(axchild(i), 'Children'),axpos,groupax,projection);

Georg Stillfried

### Georg Stillfried (view profile)

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 (converter@juergschwizer.de).
??? 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

### Georg Stillfried (view profile)

very nice, works well

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

Hello,

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(.........)
plot2svg('filename.svg',h)
The correct way to get a handle is:
h = figure(1)
surf(.........)
plot2svg('filename.svg',h)

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
chwizer.de).
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
originalFigureUnits=get(id,'Units');

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:

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

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,
edge_opacity,id)

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);

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

Thanks
-Kaushik

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!

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);
--with:
group=axchild2svg(fid,id,axIdString,ax,group,paperpos,get(axchild(i), 'Children'),axpos,groupax,projection);
--Done.

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
label2svg(fid,grouplabel,axpos,ax,xg_label_end(i),yg_label_end(i),convertString(axlabelx(i,:)),'Center',0,'top',1,paperpos,scolorname,exponent);

Error in ==> plot2svg at 139
group=axes2svg(fid,id,ax(j),group,paperpos);"

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

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'

PONTHEP VENGSUNGNLE

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

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.

Hi

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];
patch('Faces',fac,'Vertices',vert,'FaceVertexCData',tcolor,'FaceColor','flat')

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.

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!

 17 Sep 2012 1.8 - 1xn char arrays for tick labels - Fix for 'Index exceeds matrix dimensions' - Fix for another axis label problem - Fix for line style none of rectangles - Enabled scatter plot functionality 21 May 2012 1.7 - Fix for degree character - Fix for problems with dash-arrays - Modified shape of triangles - Removed versn as return value of function fileparts - Fix for images 29 Nov 2010 1.6 - Bugfix for ticklabels outside of the axis limits - Enabled scatter plots using hggroups - Closing patches if they do not contain NaNs - Support of the 'Layer' keyword to but the grid on top of of the other axis content using 'top' 6 Mar 2010 1.5 Bugfixes and support of user requests. See 'Changes in Version 06-Mar-2010' for more information. 16 Aug 2009 1.4 - Bug fixes for text size / line distance - Support of background box for text - Improved support of filters - Experimental support of animations - Rework of latex string handling - 'sub' and 'super' workaround for Firefox and Inkscape 20 Jul 2009 1.3 Improved SVG filter support, bugfixes, improved text support, more examples for the advanced filter usage. 15 Jul 2009 1.2 Bugfixes and preliminary support of SVG filters, clipping, and improved axis tick labels. 30 Jun 2009 1.1 Several bugfixes and better support of 3D graphics 20 Jan 2006 New version supporting 3D plots (please replace zip file and description) Many thanks Juerg Schwizer 9 Jan 2006 3D Version PLEASE UPDATE FILE AND DESCRIPTION 8 Dec 2005 Changes of Version 12-Dec-2005 - bugfix for Firefox 1.5 - improvement of the axis scaling - improvement handling of exponents - bugfix axindex - bugfix cell array cells - improved handling of pixel images - improved markers 23 May 2005 Updated Version 22-May-2005 - bugfix line color - bugfix path of linked jpeg figures - improved patch handling - support of pcolor plots 23 May 2005 Updated Version 22-May-2005 - bugfix line color - bugfix path of linked jpeg figures - improved patch handling - support of pcolor plots
MATLAB 6.5 (R13)