Add multiple legends to graph

조회 수: 12 (최근 30일)
Hannah
Hannah 2021년 8월 10일
댓글: Hannah 2021년 8월 11일
I see a scatter plot that use different shapes of marker to indicate the source of data while using different color to indicate the area that each data point cover. I am able to produce the scatters but I don't know how to orgnize the legend like that.
If I use the default legend function in MatLab, it will give me all the combination of markers, which is lengthy.
Anyone know how to display the shape of marker and the color of marker seperately?

채택된 답변

Dave B
Dave B 2021년 8월 10일
편집: Dave B 2021년 8월 10일
You can't (easily) make multiple legends, but you can make a 'fake' legend by including some objects in your chart that have NaN data and telling legend to use those objects:
% Fake data: 3 colors by 3 markers, would be 9 legend items
scatter(randn(10,1),randn(10,1),'ro')
hold on
scatter(randn(10,1),randn(10,1),'bo')
scatter(randn(10,1),randn(10,1),'mo')
scatter(randn(10,1),randn(10,1),'r*')
scatter(randn(10,1),randn(10,1),'b*')
scatter(randn(10,1),randn(10,1),'m*')
scatter(randn(10,1),randn(10,1),'rs')
scatter(randn(10,1),randn(10,1),'bs')
scatter(randn(10,1),randn(10,1),'ms')
% Make some data just for legend:
hLeg = gobjects(6,1);
% I used a . marker for colors, maybe a good idea to use something not in
% your 'real' markers
hLeg(1) = scatter(nan,nan,'r.');
hLeg(2) = scatter(nan,nan,'b.');
hLeg(3) = scatter(nan,nan,'m.');
% Similarly I used black for markers
hLeg(4) = scatter(nan,nan,'ko');
hLeg(5) = scatter(nan,nan,'k*');
hLeg(6) = scatter(nan,nan,'ks');
legend(hLeg, 'red', 'blue', 'magenta', 'circle', 'asterisk', 'square')
  댓글 수: 2
Dave B
Dave B 2021년 8월 10일
Similar approach with a mixed legend and colobrar:
scatter(randn(10,1),randn(10,1),40,randi(3,10,1),'o','filled')
hold on
scatter(randn(10,1),randn(10,1),40,randi(3,10,1),'*')
scatter(randn(10,1),randn(10,1),40,randi(3,10,1),'s','filled')
colormap(lines(3))
hLeg = gobjects(3,1);
hLeg(1) = scatter(nan,nan,'ko','filled');
hLeg(2) = scatter(nan,nan,'k*');
hLeg(3) = scatter(nan,nan,'ks','filled');
leg=legend(hLeg, 'circle', 'asterisk', 'square');
c=colorbar;
c.Ticks = [4/3 2 8/3];
c.TickLabels = ["color 1" "color 2" "color 3"];
Hannah
Hannah 2021년 8월 11일
Thank you Dave! This is super helpful!
Haihui

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

추가 답변 (0개)

카테고리

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