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!

采纳的回答

Shubham
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!
  2 个评论
Bernd
Bernd 2024-9-23
Thanks! The solution I was looking for was explained in the link provided and works quite well after few code adjustments.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

产品


版本

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by