Why is the marker size in the legend of a scatter plot not equal to the marker size in the plot?

조회 수: 16 (최근 30일)
If I execute the following code, the marker size in the legend is different from that in the scatter plot:
figure; hold on
s1 = scatter(1, 1, 150, 'k', 'o')
s2 = scatter(1, 2, 150, 'k', '+')
s3 = scatter(2, 1, 150, 'k', 'x')
h = legend('Circle', 'Plus', 'X', 'Location', 'NorthEast');
set(h, 'FontSize', 14)
axis([0 3 0 3])
How can I set these marker sizes to be equal when using the "scatter" function?

채택된 답변

MathWorks Support Team
MathWorks Support Team 2024년 10월 18일
편집: MathWorks Support Team 2024년 10월 31일
The ability to automatically equalize the marker size of the legend and plot markers when using the "scatter" function is not available in MATLAB 7.9 (R2009b).
You may use either of the following workarounds to create a scatter plot in which the legend markers have the same size as the plot markers:
1. Manually set marker sizes in the legend
  • For MATLAB R2014a and prior releases, manually set the marker size of the patch objects in the legend. Note that the marker area input to the "scatter" function is specified in square points, whereas the 'MarkerSize' property of a patch object is given in points:
M = findobj(h,'type','patch') % Find objects of type 'patch'
set(M,'MarkerSize', sqrt(150)) %Calculate marker size based on size of scatter points
  • For MATLAB R2014b to MATLAB R2024b, use the following syntax. This is due to a change in the legend graphics object hierarchy. This also enables setting each marker size in the legend, if different sizes are desired to match the different sizes of points in a figure.
[h, icons] = legend('Circle', 'Plus', 'X', 'Location', 'NorthEast');
icons(4).Children.MarkerSize = sqrt(150);
icons(5).Children.MarkerSize = sqrt(150);
icons(6).Children.MarkerSize = sqrt(150);
Note: support for multiple outputs of the "legend" function is still provided for MATLAB R2024b, but it is expected to be removed in a future release of MATLAB.
2. Use the "plot" function instead of the "scatter" function:
figure; hold on
plot(1,1,'ko', 'MarkerSize', 12)
plot(1,2,'k+', 'MarkerSize', 12)
plot(2,1,'kx', 'MarkerSize', 12)
h = legend('Circle', 'Plus', 'X', 'Location', 'NorthEast');
set(h, 'FontSize', 14)
axis([0 3 0 3])
Another possible approach with the "plot" function is to use the following syntax. This also enables setting each marker size in the legend, if different sizes are desired to match the different sizes of points in a figure.
[h, icons] = legend('Circle', 'Plus', 'X', 'Location', 'NorthEast');
icons(4).MarkerSize = sqrt(150);
icons(5).MarkerSize = sqrt(150);
icons(6).MarkerSize = sqrt(150);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by