Legend with two colors same as surface colors

7 ビュー (過去 30 日間)
Bernd
Bernd 2024 年 9 月 22 日
コメント済み: Shubham 2024 年 9 月 23 日
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.
Shubham
Shubham 2024 年 9 月 23 日
Glad to know the issue has been resolved!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLegend についてさらに検索

製品


リリース

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by