St-Ste-Ste-Stephen
St-Ste-Ste-Stephen

Reputation: 1076

Plotting a subplot on top of another plot in Matlab

I need to plot several plots along a sloped line at different positions.

For example, if I:

plot(0:200,'k');
plotpts = 5:5:200;

I would like to be able to plot a smaller plot at each of my plotpts on top of the original 0:200 line.

I know you can use hold on and plot over top that way, but I need to change my origin each time. Does anyone have any suggestions? I would really like to stay in matlab. Thanks!

Upvotes: 3

Views: 4707

Answers (3)

John Colby
John Colby

Reputation: 22588

Here is a flexible way I usually do it:

plot(1:10, 'k')
plotpts = 2:2:8;

mainbox = get(gca, 'Position');
xlims = get(gca, 'XLim');
ylims = get(gca, 'Ylim');

for i=1:length(plotpts)
    originx = mainbox(1) + (plotpts(i) - xlims(1)) * (mainbox(3)) / (xlims(2) - xlims(1));
    originy = mainbox(2) + (plotpts(i) - ylims(1)) * (mainbox(4)) / (ylims(2) - ylims(1));

    axes('position', [originx originy 0.1 0.1], 'Color', 'none')

    % Do some plotting here...
end

enter image description here

Upvotes: 9

Pursuit
Pursuit

Reputation: 12345

It's quite a bit of work, but you probably want to use the axes command. A figure window can host any number of axes, where each axes has it's own position, data, annotations, color etc.

The most difficult thing for the application you describe is that each axis position needs to be defined in the coordinate frame of the underlying figure, which means that some math may be required to create the illusion that the axis is correctly positioned within a parent axes/

For example, if you first create a simple plot

figure(1234); clf;
plot(1:10, rand(1,10),'.k-','linewidth',5);
xlim([1 10]);
ylim([0 1]);
set(gca,'color','y');  %This just helps demonstrate the next steps

You can place another axis directly on top of the first, and then

ha = axes('position',[.2 .3 .1 .1])
plot(linspace(0,2*pi,100), sin(linspace(0,2*pi,100)), 'b-')
xlim([0 2*pi])

You can adjust the the properties of the inset axis to suit your particular needs, for example

set(ha,'color','none');  %A transparent axis
set(ha,'xtick',[],'ytick',[]);  %Remove tick labels 
title(ha,'This is an inset plot')

Upvotes: 1

Chris
Chris

Reputation: 1531

Is the command subplot not what you're looking for?

Upvotes: 0

Related Questions