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

1 次查看(过去 30 天)
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 个评论
Adam Danz
Adam Danz 2019-6-30
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

请先登录,再进行评论。

回答(1 个)

Ganesh Regoti
Ganesh Regoti 2019-7-16
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');

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by