Painting a circular graph by script written in Matlab using Excel. Working with COM\VBA - matlab

I need to write a script in Matlab, which will read some data from Excel table and paint a circular graph in Matlab's figure. However I was adviced to paint it using Excel facilities. It's not hard to paint a circular graph in Excel but I still haven't found any way to make it work from Matlab, using Matlab's figure. I've already asked this question on other forums but haven't receive any answer. I'll be very grateful for any help.

So, I figured out how to use ActiveX control in Matlab's figure.
Firstly, you need to install driver mschrt20.ocx (is free and available to download from the internet). In 32-bit system you must put it in C:/System32 then install it by typing 'regsvr32 mschrt20.ocx' in cosole (as Administrator).
Then create a Matlab figure and put an ActiveX object to it, save. To activate it type to Matlab's interpretator something like this:
anyone = actxcontrol('MSChart20Lib.MSChart.2');
anyone.get;
get(anyone,'ChartData')
Now you could see all the properties of the object. In guide choose the right property 'charType' and make field 'Legend' 'Visible' if you need it.
To paint a pie chart using your ActiveX object you need to set the meaning of it's field 'ChartData'. It's a cell 2xn. Use it as in the example below:
S = cell(2, 3);
S(1,: ) = {'first', 'second', 'third'} ; %legend
S(2,: ) = {1, 10, 5} ; %meanings
set(handles.activex1,'ChartData', S);
That's how it works. There some other abilities available with ActiveX control.

There are a lot of ways to understand your question:
If you want a pie chart, matlab can do that with the 'pie' function:
http://www.mathworks.com/help/techdoc/ref/pie.html
x = [1 3 0.5 2.5 2];
explode = [0 1 0 0 0];
pie(x,explode)
colormap jet
If you wanted to actually plot a circle, then you would use the 'rectangle' command with 'Curvature' settings like this:
rectangle('Position',[1,2,5,10],'Curvature',[1,1],...
'FaceColor','r')
daspect([1,1,1])
xlim([0,7])
ylim([1,13])
Or you could look at these sites for alternatives for drawing a circle:
http://blogs.mathworks.com/pick/2008/03/21/drawing-a-circle/
http://www.mathworks.com/matlabcentral/fileexchange/2876
If instead you wanted polar axes:
http://www.mathworks.com/help/techdoc/ref/polar.html
figure
t = 0:.01:2*pi;
polar(t,sin(2*t).*cos(2*t),'--r')
The following is the equation for a circle (and so you'll see a red circle overlaid over the black polar plot axes:
polar(t,sin(t).^2+cos(t).^2,'--r')

Related

matlab dynamic scrolling in figures

I've added a number of timeseries to a figures object in Matlab and plotted them as subplots on the graph to display them all together, one after the other. There can be a dynamic number of timeseries plots, I can't know in advance how many there will be.
Unfortunately what seems to be happening is that the figures plot is not expanding to include a scroll bar as new subplots are added. Is there a particular flag I'm not seeing to include this and stop the plots in my figures object from getting smaller and smaller?
As an example:
%Maximise the figure window to full screen
f = figure;
f=gcf;
f.Units='normalized';
f.OuterPosition=[0 0 1 1];
%Add a panel to the figure, we'll add subplots to this
p = uipanel('Parent',f,'BorderType','none');
p.Title = 'Examples';
p.TitlePosition = 'centertop';
p.FontSize = 12;
p.FontWeight = 'bold';
%Add a timeseries subplot to the panel
subplot((length(motifIndexAfterThresholds)*2)+1,1,1, 'Parent',p)
ts0 = timeseries(E4_hrX(startIndex:endIndex),'Name','Parent Motif');
plot(ts0)
title('Parent')
After this point I could add in as many subplots as I like, but the panel is not stretching as I'd have hoped.
If anyone can offer suggestions I'd very much appreciate it.
Anyone with the same problem, check out this (2011) blog post:
https://blogs.mathworks.com/pick/2011/11/23/scrolling-figures-guis/
It turns out that a user submitted function can provide this functionality, and all we need to do is download that .m file, include it in your Matlab path, change the function call from subplot to scrollsubplot in our code.
No idea if this will work long term, a feature like this probably should be included out of the box by matlab itself.

plot a hi res compass rose in matlab

I'm trying to figure out how to plot a 1-degree resolution compass rose in matlab, that looks something similar to this:
I have tried various compass and polar plots but they don't seem to allow customizing the appearance of the scale around the plot. I can only get a basic 30 degree grid.
Update/Answers to comments:
I'm building a map using azimuthal prjection:
ax=axesm ('eqdazim', 'Frame', 'on', 'Grid', 'on')
this generates a vector image like this:
the next step is to add the shapeimage (which I already figured out) and a compass grid around it.
I want to generate a high quality/large print so I'm trying to stay in the vector format
But this does not need to be done in matlab, if there is a better tool for it. I just thought it would be easier to do the whole thing in one package. No experience with LaTeX but will look into it. A quick/scriptable process is important.
You could play with the options of
Advanced Polar Plots v2
Comprehensive Polar Plots
from the File Exchange.
e.g.: Advanced Polar Plots v2:
pp(0:1,0:1,'ThetaDirection', 'cw', ...
'ThetaStartAngle', 270, ...
'AngleStep', 1, ...
'AngleLabelStep', 10, ...
'AngleAxisStyle', '.', ...
'RingAxis', 'off')

Jagged outline using Matlab 2014b

I am plotting some maps using Matlab that use mapshow to plot the country border from a shapefile. I then export them to both a PDF and EPS format using the export_fig package. This worked completely fine using Matlab 2014a, but I have just upgraded to Matlab 2014b to take advantage of something else that has improved, and now my country border is all jagged. The border only looks jagged on the saved versions of the file. If I zoom in on the figure window, the outline isn't like that.
Here are the snippets of code that are important. It is a custom shapefile, so I don't know how to put it on here so people can replicate it.
This bit reads in the shapefile and plots it. The display type is 'polygon' if that is relevent, hence getting rid of the 'FaceColor' so I can see what I am plotting underneath (the green bits in the background of the images, plotted using pcolor).
thaiborder=shaperead('Thailandborder');
mapshow(thaiborder,'FaceColor','none');
This bit is how I am exporting the figure.
export_fig test.eps -r600 -painters
export_fig test.pdf -r600 -painters
This is the version with a smooth border from Matlab 2014a:
This is roughly the same area of the image, with the jagged border from Matlab 2014b:
Does anyone know why these differences are occurring? I want the border to be like it is in the first image, but I need the "improved" functionality of Matlab 2014b for another thing in the same image. What do I need to change?
Edit to add: I have been in contact with the creator of export_fig and he thinks it is caused by Matlab now using mitred joins rather than round ones. Apparently I have to write to MathWorks to complain. I didn't put this as an answer because someone else may be able to provide a solution for me.
Matlab acknowledged that this is known bug. For me the first fix worked.
The issue of jagged lines on the figures while exporting in the vector format is a known bug in MATLAB R2014b. It is associated with the combination of linejoins and meterlimits used in vector format.
To work around this issue, use the attached function fixeps to post process the EPS file.
You can use one of the following ways to call this fixeps function.
fixeps('input.eps','output.eps','LJ') % Will change the linejoins to round
fixeps('input.eps','output.eps','ML') % Will correct the miterlimit
function fixeps(inname,outname,fixmode)
if nargin==2
fixmode = 'LJ';
end
fi = fopen(inname,'r');
fo = fopen(outname,'w');
tline = fgets(fi);
while ischar(tline)
if (strcmp(tline,['10.0 ML' 10])) % Replace 10.0 miterlimit
switch (fixmode)
case 'LJ'
fwrite(fo,['1 LJ' 10]); % With round linejoin
case 'ML'
fwrite(fo,['2.5 ML' 10]); % With smaller miterlimit
end
else
fwrite(fo,tline);
end
tline = fgets(fi);
end
fclose(fo);
fclose(fi);
I had a similar problem that I found to be caused by the 'MarkerSize' option. It seems that in version 2014b it inherits the units of the figure. For example, if I have a figure in centimeters and I ask for ('MarkerSize', 10), the 10 will not be interpreted as points (as in 2014a) but as cm. I fixed this by changing the figure units to pt.

MATLAB: Interactive tool to "draw" a Plot?

Do you know a simple way to draw arbitrary splines or lines in a plot-figure? I've got the following figure which I created in powerpoint with more or less arbitrary spline-curve (blue) but I'd like to do the same in MATLAB now because of a better look in the final plot-output.
I'm now wondering if I've got to manually "find" data-values to draw some sort of spline (which looks roughly like the blue one below) myself or if there's maybe a tool where I can simply insert some points into a plot interactively and there's a curve fitted though it to create something similar!?
The green and red lines I can figure out myself (probably also have to plot them manually, do I)?!?
Thanks in advance!
EDIT
Okay I found a way myself doing it in MATLAB to gnerate a nice spline: Use splinetool, then either use an example or import some data and then you can interactively add and delete points until your spline looks roughly like it should. Then file->print to figure and then tools->edit plot! You can then delete everything you don't need, add title, xlabel and ylabel etc. and then export it to latex with e.g. matlab2tikz :-) Very nice stuff!!
According the purpose, print nice plots for the thesis, I have some out-of-Matlab recommendations.
1) plot everything as usual, you get a figure handle and an axes handle
h = figure( ... )
a = gca
2) use the data cursor function of the figure window and interactively insert the base points for your later splines. You can additional points by right-click.
t = linspace(0,2*pi,1000);
[x y] = deal(sin(t),cos(t))
Later you delete the "visual" part of the data tip inside Illustrator/Inkscape, if you just want to keep the anchor point of the vector graphic to snap your splines.
There is also the possibility of custom data tips: Tutorial at Matlab Central
3) I once wrote a function to nicely plot Matlab figures as vector graphic based PDFs. You can specify height, width and how much white margin around you want. You just need to pass figure and axes handle and the name:
function saveFigure( fig_handle, axes_handle, name , height , width , margin)
set(axes_handle,'LooseInset',get(gca,'TightInset'));
set(fig_handle, 'Units','centimeters','PaperUnits','centimeters')
% the last two parameters of 'Position' define the figure size
set(fig_handle,'Position',[-margin -margin width height],...
'PaperPosition',[0 0 width+margin height+margin],...
'PaperSize',[width+margin height+margin],...
'PaperPositionMode','auto',...
'InvertHardcopy', 'on',...
'Renderer','painters'... %recommended if there are no alphamaps
);
saveas(fig_handle,name,'pdf')
end
4) You get a PDF you could directly use for Latex - for use in MS Office use 'emf' (
Enhanced metafile) rather than 'pdf'. Open this file with Adobe Illustrator (preferable as it offers layers) or Inkskape (Open Source).
5) The datatips are recognized as graphical objects, you can catch them and draw a spline on them. For Illustrator I'd recommend to put the spline in another layer than the actual figure. Later you can just swap the figure and give the spline new anchor points. In Inkscape you could use the grouping function to keep everything together.
6) I'd say you save a lot of time over a only-Matlab-solution. Good look!

How to draw good looking arrows in Matlab?

I have been trying to draw arrows in Matlab in my figure but they all look terrible.
Also, I want my arrowhead to be a solid triangle, not a V.
I tried using the packages available on the Matlab File Exchange: arrow, arrows, arrows3, and probably at least one other one.
I even tried manually creating an arrow in the Matlab figure editor, but when I adjust the line width, the arrow looks like this:
I used the annotation command to create the arrow above:
annotation(gcf,'arrow',[0.621875 0.457916666666667],...
[0.205421152030217 0.40755429650614],...
'HeadLength',4,'LineWidth',5);
Here's the result trying to use the arrow package available here: Arrow.m (notice how the bottom arrow head is not perpendicular to the line:
I even tried the following and here is the result below (notice the terrible looking arrowhead):
figure
plot(1:10, 1:10)
annotation(gcf,'arrow',[0.621875 0.457916666666667],...
[0.205421152030217 0.40755429650614],...
'HeadLength',4,'LineWidth',5);
Vector graphics is hard. Though Matlab's typography is just as bad, but here's a simplistic text-based solution (I refuse to do this sort of annotation in Matlab any more):
figure
plot(1:10, 1:10)
text(5,4,'\rightarrow','FontSize',54,'Rotation',135,...
'HorizontalAlignment','center');
which yields a figure like this
Note that I have used '\leftarrow' because it points in the direction of zero degrees, which makes doing math in my head easier. This is no canned solution, you'll still need to fiddle with position to overcome the fact that Matlab is aligning this as text (see the 'Extent' and 'Margin' properties). Not surprisingly, you may see small glitches. The LaTeX interpreter can be used to obtain a different style arrow head:
text(5,4,'$\rightarrow$','FontSize',54,'Rotation',135,...
'HorizontalAlignment','center','Interpreter','latex');
I don't get the small glitches with this option, but the arrows look different (there are likely other LaTeX arrow styles that could be substituted). Changing the font may also have an effect and there are certainly other text-based arrows that could be used. More details on adding arrows can be found in this article from The MathWorks.
Another solution is to use the open-source Waterloo graphics - a library that addresses this by providing a pure Java library of 2D graphics functions that can easily be integrated in Matlab. See some examples here...
For example, try this code (after properly installing waterloo)
f = GXFigure();
x = -5:0.1:5;
gr1 = gxgca();
a1 = line(gr1, x, cos(x), 'LineSpec','-ob');
b1 = line(gr1, x, sin(x), 'LineSpec','-sg');
annotation(gr1,'arrow',[0.1 0.1],[0.4 0.4],'HeadLength',0.2,'HeadWidth', 0.5, 'LineWidth',2);
gr1.getObject().getView().autoScale();
Having worked with Matlab for more than 10 years and seeing almost zero progress in the quality of the plots (anti-aliased output to bitmap, decent looking eps-files, ...), I decided that my long time solution will be here. Some examples of decent looking arrows here, more beautiful graphs here. Unfortunately, some of the toolboxes prevent me from going completely to numpy/scipy/matplotlib. I know this is more of a rant than an answer, but that is my solution ...
Using quiver or quiver3 for 3-D plots will certainly look better than the that last arrow you made using annotation. I'm not sure it will look much better than the ones you made using the Arrow.m package though. It's possible to change the stlyes on quiver as well if you want.
I resorted to installing InkScape and drawing arrows in there. Nothing beat the simplicity and quality.
InkScape Website
When line-based arrows fail, you can always try patch-based ones:
xArrow = [0 1 1 1.2 1 1 0]; % X-coords of arrow edge points
yArrow = [-0.1 -0.1 -0.2 0 0.2 0.1 0.1]; % Y-coords of arrow edge points
hArrow = fill(xArrow,yArrow, [1 0 0]); % Plot a red arrow
axis equal % Set axis tick marks to be equal
Although more work, you can potentially parameterize the above into a function that takes a number of arguments for adjusting the scaling, aspect ratio, rotation, and position of the arrow. You can even adjust the color, edge line color, and alpha transparency.
This sort of idea appears to have been implemented by François Beauducel in his File Exchange submission ARROWS: generalized 2-D arrows plot.
There is now the DaVinci Draw toolbox (full disclosure: I wrote/sell the toolbox), which uses low-level Matlab commands like plot() and patch() to draw mid-level shapes like arrows. Example syntax:
davinci( 'arrow', 'X', [0 10], ...
'Y', [0 2], ...
'Shaft.Width', 1, ...
'Head.Length', 2.5, ...
'Color', 'w', ...
'EdgeColor', 'k', ...
'LineWidth', 2.5 )
From the documentation: