Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlaying two axes in a Matlab plot

Tags:

plot

matlab

I am looking for a way to overlay an x-y time series, say created with 'plot', on top of a display generated by 'contourf', with different scaling on the y-axes.

It seems that the typical way to do this in the case of two x-y plots is to use the built-in function 'plotyy', which can even be driven by functions other than 'plot' (such as 'loglog') as long as the input arguments remain the same (x,y). However, since in my case contourf requires three input arguments, 'plotyy' seems to not be applicable. Here is some sample code describing what I would like to do:

x1 = 1:1:50;
y1 = 1:1:10;
temp_data = rand(10,50);
y2 = rand(50,1)*20;
figure; hold on;
contourf(x1,y1,temp_data);
colormap('gray'); 
plot(x1,y2,'r-');

Ideally, I would like the timeseries (x1,y2) to have its own y-axes displayed on the right, and be scaled to the same vertical extent as the contourf plot.

Thanks for your time.

like image 423
FoxRyerson Avatar asked Oct 24 '13 14:10

FoxRyerson


People also ask

How do I add a secondary axis to a plot in MATLAB?

Plot Data Using Two y-Axes Plot a set of data against the left y-axis. Then, use yyaxis right to activate the right side so that subsequent graphics functions target it. Plot a second set of data against the right y-axis and set the limits for the right y-axis.

How do you plot a 3 axis graph in MATLAB?

plot3( X , Y , Z ) plots coordinates in 3-D space. To plot a set of coordinates connected by line segments, specify X , Y , and Z as vectors of the same length. To plot multiple sets of coordinates on the same set of axes, specify at least one of X , Y , or Z as a matrix and the others as vectors.


1 Answers

I don't think there's a "clean" way to do this, but you can fake it by overlaying two axes over each other.

x1 = 1:1:50;
y1 = 1:1:10;
temp_data = rand(10,50);
y2 = rand(50,1)*20;
figure;
contourf(x1, y1, temp_data);
colormap('gray');
h_ax = gca;
h_ax_line = axes('position', get(h_ax, 'position')); % Create a new axes in the same position as the first one, overlaid on top
plot(x1,y2,'r-');
set(h_ax_line, 'YAxisLocation', 'right', 'xlim', get(h_ax, 'xlim'), 'color', 'none'); % Put the new axes' y labels on the right, set the x limits the same as the original axes', and make the background transparent
ylabel(h_ax, 'Contour y-values');
ylabel(h_ax_line, 'Line y-values');

In fact, this "plot overlay" is almost definitely what the plotyy function does internally.

Here's example output (I increased the font size for legibility): overlaid axes

like image 82
Daniel Golden Avatar answered Oct 19 '22 14:10

Daniel Golden