2
votes

I am trying to follow MATLAB's documentation here Graph with Multiple x-axes and y-axes to plot with 2 x and y-axes, but instead with plots rather than lines. This is what I have so far:

  clear all; close all; clc; 
 % Arbitrary x's and y's
  x1 = [10 20 30 40];
  y1 = [1 2 3 4];
  x2 = [100 200 300 400];
  y2 = [105 95 85 75];

 figure
 plot(x1,y1,'Color','r')
 ax1 = gca; % current axes
 ax1.XColor = 'r';
 ax1.YColor = 'r';
 ax1_pos = ax1.Position; % position of first axes
 ax2 = axes('Position',ax1_pos,...
     'XAxisLocation','top',...
     'YAxisLocation','right',...
     'Color','none');

 %line(x2,y2,'Parent',ax2,'Color','k') <--- This line works
 plot(ax2, x2, y2) <--- This line doesn't work

I've looked the plot documentation 2-D line plot but cannot seem to get plot(ax,__) to help/do what I expect.

The figure ends up not plotting the second plot and the axes end up overlapping. Any suggestions how to fix this and get 2 axes plotting to work? I'm currently using MATLAB R2014b.

1

1 Answers

3
votes

Finally figured this one out after trying to think about MATLAB's hierarchy of setting things.

The plot seems to reset the axis ax2 properties so setting them before plot doesn't make a difference. line doesn't do this it seems. So to get this to work with plots I did the following:

clear all; close all; clc; 
% Arbitrary x's and y's
x1 = [10 20 30 40];
y1 = [1 2 3 4];
x2 = [100 200 300 400];
y2 = [105 95 85 75];

figure
plot(x1,y1,'o', 'MarkerEdgeColor', 'r', 'MarkerFaceColor', 'r')
ax2 = axes('Color','none'); % Create secondary axis
plot(ax2, x2,y2,'o', 'MarkerEdgeColor', 'b', 'MarkerFaceColor', 'b')
% Now set the secondary axis attributes
ax2.Color = 'none'; % Make the chart area transparent
ax2.XAxisLocation = 'top'; % Move the secondary x axis to the top
ax2.YAxisLocation = 'right'; % Move the secondary y axis to the right

enter image description here