legend not showing proper titles for the legend just stuck on one

2 vues (au cours des 30 derniers jours)
Christopher Schacht
Christopher Schacht le 30 Juin 2019
clear
clc
data = xlsread('something.xlsx');
x = data(:,1);
y = data(:,2);
n = length(x);
sum_x = sum(x);
sum_y = sum(y);
sum_xy = sum(x.*y);
sum_x2 = sum(x.^2);
a1 = (n*sum_xy - sum_x*sum_y) / (n*sum_x2 -sum_x^2)
a0 = (sum_y/n) - (a1 * sum_x/n)
str = ['The line of best fit that fits your data is y = ',...
num2str(a1),'x + ',num2str(a0),...
'. Please enter value of x for which you would like a value of y computed.'];
new_x = inputdlg(str);
new_x = str2num(new_x{1});
new_y = a1*new_x + a0;
disp(['The value of y, as predicted by the line of best fit, for the value of x you provided, is ',num2str(new_y)]);
plot(x,a1,'ob',x,a0,'gs',x,new_y,'pr')
xlabel('x value')
ylabel('y value')
title('linear regression')
grid on
axis([0 100 -1 50])
pause(1);
legend('slope','y-int','new value','Location','Southwest')
hold on
  1 commentaire
Adam Danz
Adam Danz le 30 Juin 2019
Could it be that your a1, a0, or new_y values are empty or filled with NaNs?
When I supply your code with values, the legend appears as expected (see below).
plot(1:10,1:10,'ob',1:10,(1:10).*2,'gs',1:10,(1:10).*3,'pr')
xlabel('x value')
ylabel('y value')
title('linear regression')
grid on
legend('slope','y-int','new value','Location','Southwest')
190630 195324-Figure 1.jpg

Connectez-vous pour commenter.

Réponses (1)

Ganesh Regoti
Ganesh Regoti le 16 Juil 2019
Hey Christopher,
From your question, I understand that the legend is not reciprocating appropriate markers. Since you are trying to plot a vector against an integer in the same figure, using the legend command is resulting in incorrect results. To resolve this issue, consider using a vector of same integer instead –
a1 = a1.*ones(length(x),1);
a0 = a0.*ones(length(x),1);
new_y = new_y.*ones(length(x),1);
plot(x,a1,'ob',x,a0,'gs',x,new_y,'pr');
Now, when you run the following command, you will get the appropriate results
legend({'slope','y-int','new value'},'Location','southwest');

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by