I want to add a 45-degree line on my plot. I tried some ways (including refline) all give me a 38-degree line!

280 views (last 30 days)
Hey all
I wanted to have a 45-degree reference line on my plot. I searched and found there is a function namely refline so I use it but as you can see here it renders me a 38-degree line:
I even used
axis equal
but another problem appears. I mean although the line converted to 45 degrees but some space appears on my graph that is not good:
Here is the code that I used:
MONTHLY = scatter(X, Y)
axis equal
As a result, I want something like a black line this graph:
In order to compare trendline (red line) with the perfect condition (45-degree black line).
I attach my X and Y.
Thank you so much

Accepted Answer

Birdman on 1 Apr 2020
Edited: Birdman on 1 Apr 2020
Try the following:
figure(1);hold on;
plot(0:600); %45 degree line
plot(0:600,0.73*(0:600)+6.47); %trend line
legend('X-Y Line','45 degree Line','Trend Line')
BN on 2 Apr 2020
Dear Birdman,
Thank you so much again. Why this method does not work well on my other X and Y points? I even use Walter Roberson xlim() and ylim() suggestion but the 45-degree line won't draw correct.
Look, I use this code:
hold on;
class1 = scatter(X,Y,12,'k','filled');
[pp,s] = polyfit(X,Y,1);
r_squared = 1 - s.normr^2 / norm(Y-mean(Y))^2;
R2 = r_squared;
plot(1:max(X),pp(1)*(1:max(X))+pp(2)); %trend line
str = {sprintf('y = %.2fx+%.2f',pp(1),pp(2)),sprintf('R^2 = %.2f',r_squared)};
annotation('textbox', [0.2, 0.75, .1, .1], 'String',str ,'FitBoxToText',...
'on','fontname','Cambria Math','HorizontalAlignment', 'center',...
'FontSize',8,'BackgroundColor', 'white');
set(gca,'fontname','Times New Roman','FontSize',8) % Set it to times
box on;
grid on
plot(1:max(X),'k'); %45 degree line <<<<<<<<<<<<<<<<
xlim([0 max(X)])
ylim([0 max(Y)])
And here is the results:

Sign in to comment.

More Answers (2)

Ameer Hamza
Ameer Hamza on 1 Apr 2020
Edited: Ameer Hamza on 1 Apr 2020
Explicitly specify slope with refline
MONTHLY = scatter(X, Y)
axis equal
Or draw both lines
MONTHLY = scatter(X, Y)
r1 = refline;
r1.LineWidth = 1;
r2 = refline(1);
r2.LineWidth = 1;
axis equal
  1 Comment
BN on 2 Apr 2020
Thank you so much I tried this approach but I don't know why doesnt work dor me, Here is the results:
I even use xlim and ylim
xlim([0 max(X)])
ylim([0 max(Y)])
But not works.
Thank you.

Sign in to comment.

Kouadio Guillaume N'DRI
Kouadio Guillaume N'DRI on 22 Jan 2022
Edited: Walter Roberson on 23 Jan 2022
In case someone still struggling with this. Find below my suggestion. I had the same problem with the refline.
axis([0 max(max(x1),max(x2)) 0 max(max(x1),max(x2))])
hold on
plot([0 max(max(x1),max(x2))], [0 max(max(x1),max(x2))])


Find more on Line Plots in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!