Skip to content

Commit d6655b8

Browse files
Fix heatmap text color logic
1 parent 0832b9b commit d6655b8

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

plotly/Test_plotlyfig.m

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2580,5 +2580,37 @@ function testGroupedBarPlotData(tc)
25802580
showlegend = true ...
25812581
));
25822582
end
2583+
2584+
function testHeatmapTextColorBrightCells(tc)
2585+
fig = figure("Visible","off");
2586+
data = [1 2; 3 4];
2587+
h = heatmap(data);
2588+
h.Colormap = repmat([0.9 0.9 0.9], 64, 1); % Light gray colormap
2589+
2590+
p = plotlyfig(fig,"visible","off");
2591+
2592+
tc.verifyNumElements(p.layout.annotations, numel(data)+1);
2593+
% All cells should have black text due to bright background
2594+
for i = 2:numel(p.layout.annotations)-1
2595+
ann = p.layout.annotations{i};
2596+
tc.verifyEqual(ann.font.color, "rgb(0,0,0)"); % Black text
2597+
end
2598+
end
2599+
2600+
function testHeatmapTextColorDarkCells(tc)
2601+
fig = figure("Visible","off");
2602+
data = [1 2; 3 4];
2603+
h = heatmap(data);
2604+
h.Colormap = repmat([0.1 0.1 0.1], 64, 1); % Dark gray colormap
2605+
2606+
p = plotlyfig(fig,"visible","off");
2607+
2608+
tc.verifyNumElements(p.layout.annotations, numel(data)+1);
2609+
% All cells should have white text due to dark background
2610+
for i = 2:numel(p.layout.annotations)-1
2611+
ann = p.layout.annotations{i};
2612+
tc.verifyEqual(ann.font.color, "rgb(255,255,255)"); % White text
2613+
end
2614+
end
25832615
end
25842616
end

plotly/plotlyfig_aux/handlegraphics/updateHeatmap.m

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,13 +65,17 @@
6565
family = matlab2plotlyfont(heat_data.FontName) ...
6666
);
6767

68+
values = heat_data.ColorDisplayData';
6869
for i = 1:m
6970
for j = 1:n
7071
ann.text = num2str(round(cdata(j,i), 2));
7172
ann.x = i-1;
7273
ann.y = j-1;
7374
ann.showarrow = false;
74-
if cdata(j,i) < 0.925*maxcol
75+
indices = find(values(:) == cdata(j,i));
76+
colorIndex = indices(1);
77+
c = 255*cmap(colorIndex,:);
78+
if 442*c(1) + 867*c(2) + 170*c(3) - 189006 > 0
7579
col = [0,0,0];
7680
else
7781
col = [255,255,255];

0 commit comments

Comments
 (0)