File Exchange

image thumbnail

set2xyaxis

version 1.0.1 (1.57 KB) by Kevin Chng
Plot 2 y-axis and 2 x-axis in a graph. It allows user to zoom in and out of the graph with correct scales of both x and y axis.

1 Download

Updated 01 Sep 2018

View Version History

View License

With linkaxes function, your scale limit for both x-axis or y-axis are same.
It does not allow user to zoom it and out with different scale of the both x-axis or both y-axis.
It can be solved by set2xyaxis and it allows user to zoom in and out of the graph.

% set2xyaxis help you to set the 2nd axis with different scales
% zoom function is built to allow user to zoom in and out of graph
% The scale of two axis will follow the zoom proportionally.
%
% set2xyaxis(labelx1, labely1,labelx2,labely2,xlim2,ylim2)
% Example :
% figure
% x1 = 0:0.1:40;
% y1 = 4.*cos(x1)./(x1+2);
% line(x1,y1,'Color','r')
% set2xyaxis('ni hao','da jia hao','hao ma',1,[0 2],[30 40]);
%
% Copyright 2018 Kevin Chng. kevinchng@hotmail.com

if nargin < 6
error('Not enough input arguments');
end

%% Second Axes
global ax1 scaleX

ax1 = gca;
ax1_pos = ax1.Position; % position of first axes
xlabel(labelx1);
ylabel(labely1);
ax2 = axes('Position',ax1_pos,...
'XAxisLocation','top',...
'YAxisLocation','right',...
'Color','none');
xlabel(labelx2)
ylabel(labely2)
set(ax2,'xlim',[xlim2(1) xlim2(2)]);
set(ax2,'ylim',[ylim2(1) ylim2(2)]);
grid on;

%% Count the scale
scaleX = (ax1.XLim(2)-ax1.XLim(1))/(ax2.XLim(2)-ax2.XLim(1));

%% set properties of call back function
h = zoom(ax2);
h.ActionPostCallback = @mypostcallback;
h.Enable = 'on';
end

function mypostcallback(obj,evd)
newLim = evd.Axes.XLim;
global ax1 scaleX
set(ax1,'xlim',[newLim(1)*scaleX newLim(2)*scaleX]);
end

Cite As

Kevin Chng (2021). set2xyaxis (https://www.mathworks.com/matlabcentral/fileexchange/68671-set2xyaxis), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (0)

MATLAB Release Compatibility
Created with R2018a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Tags Add Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!