How to convert coordinate in subplot into figure coordinate? - matlab

I'm trying to draw lines across images in different subplots. The basic idea is to use an annotation, thanks to this question on SO.
Here's a script on Mathworks File Exchange but it's not working on modern versions of MATLAB, and not working on axis image.

I find the answer myself.
Refer to this file on Mathworks file exchange.
It calls for a lot of nasty tricky calculations and transformations. Courtesy to Benoît Valley
First, get config of the figure,
% get axes properties
funit=get(get(h_axes,'Parent'),'Units');
% get axes properties
aunit=get(h_axes,'Units');
darm=get(h_axes,'DataAspectRatioMode');
pbarm=get(h_axes,'PlotBoxAspectRatioMode');
dar=get(h_axes,'DataAspectRatio');
pbar=get(h_axes,'PlotBoxAspectRatio');
xlm=get(h_axes,'XLimMode');
ylm=get(h_axes,'YLimMode');
xd=get(h_axes,'XDir');
yd=get(h_axes,'YDir');
% set the right units for h_axes
set(h_axes,'Units',funit);
axesoffsets = get(h_axes,'Position');
x_axislimits = get(h_axes, 'xlim'); %get axes extremeties.
y_axislimits = get(h_axes, 'ylim'); %get axes extremeties.
x_axislength = x_axislimits(2) - x_axislimits(1); %get axes length
y_axislength = y_axislimits(2) - y_axislimits(1); %get axes length
and finally
xfigure = xab+xwb*(xaxes-x_axislimits(1))/x_axislength;
Why I don't use generate code?
Generate code gives me this sort of stuff:
% Create line
annotation(figure1,'line',[0.223214285714286 0.694642857142857],...
[0.552380952380952 0.630952380952381]);
Which is not related to existing lines, points or figures, not to mention the variables not plotted. So basically I'm looking for ways to get those point positions in that annotation coordinates, which is dealt with in the above code.
If I didn't get you guys right on how to use generate code, plz let me know.

Related

MATLAB: Two different y-axis limits for Multiple plots on same graph

I need to plot two plots on same figure in MATLAB.
The maximum and minimum values in both the data samples have large variation, which I am unable to plot by taking same y-axis limits.
I do not wish to use two scales as explained in other Overlaying two axes in a Matlab plot but need to use a single y-axis and get the solution.
I tried the code:
x_axis_X = 1:length(S);
y_axis_Y = 1:length(N);
ylim([-1204200 -1841.6])
set(gcf,'color','w');
plot(x_axis_X, S,'o-', y_axis_Y, N, 'x-');
The result is as shown in the plot where one data sample is plotted without proper y-axis range.
The y limits for first data sample is -1204200 to -1841.6 and for the second it is -489429345.5 to -10408189.43.
How should be the ylim defined to fit both plots in the same figure?
I appreciate your inputs. Thank you.
In older versions of MATLAB use the function plotyy. In more recent versions of MATLAB use yyaxis. The following is the example from the documentation:
x = linspace(0,10);
y = sin(3*x);
yyaxis left
plot(x,y)
z = sin(3*x).*exp(0.5*x);
yyaxis right
plot(x,z)
ylim([-150 150])
I tried the idea of scaling one dataset so that it has a similar magnitude as the other data set. Here, I multiplied one dataset by 100 (or any suitable scaling parameter), and then it will be similar in size to the other data set. In order to clearly mention which data has been scaled in the graph I used the legend.
plot(x,data1,x,100*data2)
legend('data1','100*data2','location','southeast')
Thank you.
Scaling is not the best option, as you may need to work with the data later. Also does not work if for instance, you need a log scale.
Matlab has a few ways to deal it with. I particularly like to use a new axes in the figure, as i have done in the example below.
Just in case, you also found this answer in a simple google search!
Code:
a=1:10;
b=(10:-1:1)*100;
x=1:10;
hold on
plot(x,a,'b')
pax1=get(gca,'Position'); %get axis position
ax2 = axes('Position',pax1); %create a new axis
plot(ax2,x,b,'r') %plot new data
set(ax2, 'Yaxislocation','right',...
'color','none') % set it transparent and to the right

Matlab clabel with figure-file

I´m facing a problem. I open a figure-file (.fig) in Matlab that is a 2D contourf-plot. I created the file with a software that is based on matlab but has a GUI: maptools. I added Isolines in the plot. Each Isoline is labeled by me (clabel in matlab). The problem now is that I can´t set the space between the labels of the isolines so that each isoline has a lot of labels say for example 5.
in Matlab it is pretty easy to fix that. just the following way:
[Cp hp] = contourf(x,y,levels);
clabel(Cp,hp,'LabelSpacing',150);
My Question now is whether it is possible to read in the figure-file in Matlab with openfig(anyfigure.fig) and change the space between the isoline labels. In other words, is there any isoline (or isoline label) handle for a figure file that is opened with openfig()
Thank you ;)
When you use contour/contourf you are generating instances of a contour object that you can address directly. When loading in your figure, specify an output so you have the handle to your figure, which you can use with findobj to locate your contour object. This contour object is the second input to clabel.
For example:
filepath = 'somepath';
myfig = openfig(filepath);
# Assume only one contour object in the figure
hp = findobj(myfig.Children, 'Type', 'contour');
clabel([], hp, 'LabelSpacing', 150);
Which generates the following for a sample contour plot:
Note that clabel, per the documentation, does not need the contour matrix input C if you have the handle to the contour object. The contour matrix is a property of the object so MATLAB can get it for itself.

Plot within a plot in MATLAB

I am trying to create a smaller plot within a plot in MATLAB, for example like the image of this MATLAB File Exchange Upload.
There, two figures are created and then both of them are plotted in one figure.
My problem however is that I already have two MATLAB figures from earlier simulations and I need to embed one figure into the other one, i.e., one would be small and the other plot would be big but in the same graph. Could someone suggest an easy way to do this?
This can be done using the copyobj function. You'll need to copy the Axes object from one figure to the other:
f(1) = openfig('fig1.fig');
f(2) = openfig('fig2.fig');
ax(1) = get(f(1),'CurrentAxes'); % Save first axes handle
ax(2) = copyobj(get(f(2),'CurrentAxes'),f(1)); % Copy axes and save handle
Then you can move and resize both axes as you like, e.g.
set(ax(2),'Position', [0.6, 0.6, 0.2, 0.2]);

How to specify the axis size when plotting figures in Matlab?

Suppose that I have 2 figures in MATLAB both of which plot data of size (512x512), however one figure is being plotted by an external program which is sets the axis parameters. The other is being plotted by me (using imagesc). Currently the figures, or rather, the axes are different sizes and my question is, how do I make them equal?.
The reason for my question, is that I would like to export them to pdf format for inclusion in a latex document, and I would like to have them be the same size without further processing.
Thanks in Advance, N
Edit: link to figures
figure 1: (big)
link to smaller figure (i.e. the one whose properties I would like to copy and apply to figure 1)
For this purpose use linkaxes():
% Load some data included with MATLAB
load clown
% Plot a histogram in the first subplot
figure
ax(1) = subplot(211);
hist(X(:),100)
% Create second subplot
ax(2) = subplot(212);
Now link the axes of the two subplots:
linkaxes(ax)
By plotting on the second subplot, the first one will adapt
imagesc(X)
First, you have the following:
Then:
Extending the example to images only:
load clown
figure
imagesc(X)
h(1) = gca;
I = imread('eight.tif');
figure
imagesc(I)
h(2) = gca;
Note that the configurations of the the first handle prevail:
linkaxes(h)
1.Get the handle of your figure and the axes, like this:
%perhaps the easiest way, if you have just this one figure:
myFigHandle=gcf;
myAxHandle=gca;
%if not possible, you have to search for the handles:
myFigHandle=findobj('PropertyName',PropertyValue,...)
%you have to know some property to identify it of course...
%same for the axes!
2.Set the properties, like this:
%set units to pixels (or whatever you prefer to make it easier to compare to the other plot)
set(myFigHandle, 'Units','pixels')
set(myAxHandle, 'Units','pixels')
%set the size:
set(myFigHandle,'Position',[x_0 y_0 width height]) %coordinates on screen!
%set the size of the axes:
set(myAxHandle,'Position',[x_0 y_0 width height]) %coordinates within the figure!
Ok, based on the answer of #Lucius Domitius Ahenoba here is what I came up with:
hgload('fig1.fig'); % figure whose axis properties I would like to copy
hgload('fig2.fig');
figHandles = get(0,'Children');
figHandles = sort(figHandles,1);
ax(1) = findobj(figHandles(1),'type','axes','-not','Tag','legend','-not','Tag','Colorbar');
ax(2) = findobj(figHandles(2),'type','axes','-not','Tag','legend','-not','Tag','Colorbar');
screen_pos1 = get(figHandles(1),'Position');
axis_pos1 = get(ax(1),'Position');
set(figHandles(2),'Position',screen_pos1);
set(ax(2),'Position',axis_pos1);
This is the 'before' result:
and this is the 'after' result:
Almost correct, except that the aspect ratios are still off. Does anybody know how to equalize everything related to the axes? (I realize that I'm not supposed to ask questions when posting answers, however adding the above as a comment was proving a little unwieldy!)

Draw line between two subplots

I have two two-by-n arrays, representing 2d-points. These two arrays are plotted in the same figure, but in two different subplots. For every point in one of the arrays, there is a corresponding point i the other array. I want to show this correspondance by drawing a line from one of the subplots to the other subplot.
The solutions i have found are something like:
ah=axes('position',[.2,.2,.6,.6],'visible','off'); % <- select your pos...
line([.1,.9],[.1,.9],'parent',ah,'linewidth',5);
This plots a line in the coordinate system given by the axes call. In order for this to work for me i need a way to change coordinate system between the subplots system and the new system. Anybody know how this can be done?
Maybe there is different way of doing this. If so i would love to know.
First you have to convert axes coordinates to figure coordinates. Then you can use ANNOTATION function to draw lines in the figure.
You can use Data space to figure units conversion (ds2nfu) submission on FileExchange.
Here is a code example:
% two 2x5 arrays with random data
a1 = rand(2,5);
a2 = rand(2,5);
% two subplots
subplot(211)
scatter(a1(1,:),a1(2,:))
% Convert axes coordinates to figure coordinates for 1st axes
[xa1 ya1] = ds2nfu(a1(1,:),a1(2,:));
subplot(212)
scatter(a2(1,:),a2(2,:))
% Convert axes coordinates to figure coordinates for 2nd axes
[xa2 ya2] = ds2nfu(a2(1,:),a2(2,:));
% draw the lines
for k=1:numel(xa1)
annotation('line',[xa1(k) xa2(k)],[ya1(k) ya2(k)],'color','r');
end
Make sure your data arrays are equal in size.
Edit: The code above will do data conversion for a current axes. You can also do it for particular axes:
hAx1 = subplot(211);
% ...
[xa1 ya1] = ds2nfu(hAx1, a1(1,:),a1(2,:));
A simple solution is to use the toolbar in the figure window. Just click "insert" and then "Line".