Legend with two colors same as surface colors

7 views (last 30 days)
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!

Accepted Answer

Shubham
Shubham on 22 Sep 2024
Edited: Shubham on 22 Sep 2024
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 Comments
Bernd
Bernd on 23 Sep 2024
Thanks! The solution I was looking for was explained in the link provided and works quite well after few code adjustments.
Shubham
Shubham on 23 Sep 2024
Glad to know the issue has been resolved!

Sign in to comment.

More Answers (0)

Products


Release

R2024a

Community Treasure Hunt

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

Start Hunting!