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
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')
답변 (1개)
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');
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Legend에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!