Search code examples
matlabmatlab-figureaspect-ratio

Consistently generate line at at a specified angle as measured by user in MATLAB


Consider the simple code below that generates a straight downward sloping line in MATLAB.

clear, clc, close all

t = 0:0.1:1;
y = -t+1;


plot(t,y)
ax = gca

This is a line with slope -1, so the (acute) angle between the horizontal axis and the line is 45 degrees. Except it isn't when you measure with a protractor on your monitor.

Without changing the range of values displayed on the x and y axes or the height of the figure window, how could I ensure I would measure 45 degrees from the horizontal axis to the line if I held a protractor up to the screen?

My current approach is to change the width of the figure window. In the limit as the figure window is infinitely thin, the line x is a vertical line. Conversely, if the figure window is stretched to the edges of a monitor, it flattens out. Somewhere in the middle, the line has the angle I want. I just can't find a good way to mathematically find this point and instantiate it in code.

Edit: A slightly more generic solution for any acute angle. (I didn't test obtuse angles.)

clear, clc, close all

ang_deg = 70;
slope = tand(ang_deg);


t = 0:0.1:1;
y = -slope*t+1;

f = figure;
f.Position(3) = f.Position(3)*1.5;
plot(t,y)

% For a given height, change the width
ax = gca;
ax.Units = 'pixels';
ax.Position(3) = ax.Position(4)/slope;

Solution

  • Follow up your commands with a declaration that you'll be working in pixels, and then set the width to the height:

    ax.Units = 'pixels';
    ax.Position(3) = ax.Position(4);