Legend with two colors same as surface colors
7 次查看(过去 30 天)
显示 更早的评论
Hello,
i wanted to change the rectangle of one color in the legend with the two colors of the surface.
Code:
---------------
close all;clear;clc;
% data
x = 0:1:10;
y = 0:1:20;
Z = sin(x') + cos(y);
% creates matrix with alternating ones and zeros
CData_0101 = zeros(length(x),length(y));
for r=1:size(CData_0101,1)
for c = 1:2:size(CData_0101,2)
CData_0101(r,c) = 1;
end
if mod(r,2)
CData_0101(r,:) = circshift(CData_0101(r,:),1);
end
end
surf(x,y,transpose(Z),transpose(CData_0101));
% legend should have the same two colors as surface. How?
legend;
---------------
Afterwards i want the legend to look like this:
Has anyone a solution?
Thanks for replies!
0 个评论
采纳的回答
Shubham
2024-9-22
编辑:Shubham
2024-9-22
Hey Bernd,
For adding multiple colors in the legend, you would need to create annotations that mimics the behaviour you are aiming to achieve. Have a look at the following MATLAB Answer post suggesting a way to create legends with color gradients: https://www.mathworks.com/matlabcentral/answers/805881-how-can-i-gradient-the-legend-color-in-matlab
But if both the colors of the legend correspond to the same data, then for simplicity we can add multiple lines in the legend itself to map the color and the data it represents. For instance, I added dummy patches for adding the legend:
hold on;
% create patches for each color used in the surface plot
patch_y = patch(NaN, NaN, 'y'); % Yellow patch for legend
patch_b = patch(NaN, NaN, 'b'); % Blue patch for legend
% add custom legend
legend([patch_y, patch_b], {'data', 'data'});
I hope this was helpful!
更多回答(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!