Grid a plot with diagonal lines

85 views (last 30 days)
Srh Fwl
Srh Fwl on 28 Dec 2020
Edited: Adam Danz on 28 Dec 2020
I would like to plot a diagonal grid where there are three or four lines of positive slope=1 like in the figure attached.
I don't see an equivalent of the command, "grid" that efficiently creates a horizontal–vertical grid (maybe someone knows of one?). So instead I'm trying to do it this way, where I avoid having to hard-code anything because I have many plots and will have to update them regularly.
xL = get(gca, 'XLim');
plot(xL,xL);
This gives me one line that goes through the origin, is positive, and has slope=1. However--silly question, I know--I can't figure out how to get additional lines that parallel the line. If anyone has any hints on this, I'd be grateful.

Accepted Answer

Mischa Kim
Mischa Kim on 28 Dec 2020
There are a couple of things you could do. E.g.
x = -5:1:5; N = numel(x);
X = ones(N,1)*x;
Y = X + X';
plot(X',Y');
grid
  1 Comment
Srh Fwl
Srh Fwl on 28 Dec 2020
Thank you, Mischa; exactly what I need.

Sign in to comment.

More Answers (1)

Adam Danz
Adam Danz on 28 Dec 2020
Edited: Adam Danz on 28 Dec 2020
ConstantLine objects extend to the axis limits even when the limits change but as of r2020b, ConstantLine objects can only be vertical (xline) or horizontal (yline).
To create a diagonal constant line that extend to the axis limits even when the limits are changed, you can apply a listener that updates the line coordinates as needed.
% Set up demo
clf
ax = axes;
hold(ax, 'on')
grid(ax, 'on')
% Add reference lines using refline([slope, y-intercept])
% Alternatively, you can use r=plot() or r=line() where each line is defined
% by two and only two coordinates (x0,y0),(x1,y1).
r(1) = refline(ax, [1,-.5]);
r(2) = refline(ax, [1, 0]);
r(3) = refline(ax, [1, .5]);
set(r, {'Color'}, {'r';'b';'g'}, 'LineWidth', 2)
% Add listener to update the reference lines when the
% axis limits are changed
addlistener(ax, {'XLim', 'YLim','XLimMode','YLimMode'}, 'PostSet', @(~,~)reflineListenerFcn(ax,r));
function reflineListenerFcn(ax,r)
% Responds to changes in xlim,ylim in axes 'ax'. Updates the
% xdata and ydata for reference lines 'r'.
r(~isvalid(r)) = [];
xdata = reshape([r.XData],2,[]);
ydata = reshape([r.YData],2,[]);
slope = diff(ydata,[],1) ./ diff(xdata,[],1);
yint = ydata(1,:) - slope.*xdata(1,:);
xl = xlim(ax);
yl = ylim(ax);
newY = slope'.*xl + yint';
newX = (newY-yint')./slope';
set(r,{'XData'},mat2cell(newX,ones(size(newX,1),1),2),...
{'YData'},mat2cell(newY,ones(size(newY,1),1),2))
xlim(ax,xl)
ylim(ax,yl)
end

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!