0
votes

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

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.

3

3 Answers

1
votes

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

enter image description here

0
votes

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.

0
votes

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!

enter image description here

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