how to display correlation coefficient on graph?

How can I display the correlation coefficient on the top left of the graph like so?
%data
data1 = [9.3 480; 9.7 501; 9.7 540; 9.7 552; 9.9 547; 10.2 622; 10.5 655; 11 701; 10.6 712; 10.6 708];
data2 = [16 9.8; 9 9; 12 9; 15 9.1;10 8.8; 11 8.7;7 8.4; 2 7.8; 5 7.9;1 7.6];
%make 2 figures
figure;
% add first plot in 2 x 1 grid
subplot(1,2,1);
scatter(data1(:,1), data1(:,2), '+', 'MarkerFaceColor', 'k');
ylabel('Engineering Doctorates');
xlabel ('Cheese Consumption');
box 'on'
axis square;
axis([7 12 450 800]);
% add second plot in 2 x 1 grid
subplot(1,2,2);
scatter(data2(:,1), data2(:,2), 'x', 'MarkerFaceColor', 'k');
ylabel('Kentucky Marriage Rate');
xlabel('Fishing Boat Drownings');
box 'on'
axis square;
axis([0 20 7 10]);
%ticks off
set(gca,'Ticklength',[0 0])
%white background
set(gcf,'color','w');
%correlation coefficient
r = corrcoef(data1(:, 1), data1(:, 2));
disp(r(1,2));

댓글 수: 5

jonas
jonas 2018년 5월 18일
The code you provided seems to work fine, what is the problem?
Hi Jonas,
I am trying to display the correlation coefficient on the graph, not just in the command window. I keep getting an error message.
Hi, try adding this after the disp
str=['r= ',num2str(r(1,2))]
T = text(min(get(gca, 'xlim')), max(get(gca, 'ylim')), str);
set(T, 'fontsize', 14, 'verticalalignment', 'top', 'horizontalalignment', 'left');
which is more or less the code you provided in the attachment. Is that it?
Works perfectly! Thanks so much!
jonas
jonas 2018년 5월 18일
편집: jonas 2018년 5월 18일
Great! I will post an answer so that this question disappears from unanswered. Btw, use the code in the answer if you want less decimals.

댓글을 달려면 로그인하십시오.

 채택된 답변

jonas
jonas 2018년 5월 18일

0 개 추천

The code you attached works perfectly fine, just replace the variable names and add after your own code
tmp=corrcoef(data1(:,1),data1(:,2));
str=sprintf('r= %1.2f',tmp(1,2));
T = text(min(get(gca, 'xlim')), max(get(gca, 'ylim')), str);
set(T, 'fontsize', 14, 'verticalalignment', 'top', 'horizontalalignment', 'left');

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

질문:

2018년 5월 18일

댓글:

2021년 3월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by