How can I plot with colors and text in each grid cells?

조회 수: 38 (최근 30일)
Melih Furkan SEN
Melih Furkan SEN 2023년 11월 6일
답변: Pratik 2023년 11월 14일
I want to make similar to given photo. How do I do that? I want each cell to have color based on my input and, each cell can have my text inside. And each cell will have automatic heatmap based on 3rd value in text.

채택된 답변

Pratik
Pratik 2023년 11월 14일
Hi Melih,
As per my understanding, you want to make a heatmap which should be like the picture attached with the query. The heatmap should have colour based on the input, should have text inside and black boundaries between cells.
imagesc and ‘text’ function can be used to achieve this. ‘line’ function can be used to add boundaries on the heatmap.
  1. Assuming the values to create the heatmap are in ‘heatMapValues’ variable then using ‘imagesc’ heatmap can be created. Refer to the following code snippet.
heatMapValues = rand(4, 4); % taking random values as dummy data
% Create a heatmap
imagesc(heatMapValues);
2. Text can be written inside cell using ‘text’ function and sprintf’ can be used to format the data. The following code snippet can be used to write character ‘x’ in the cell with number ‘4’ as superscript.
% Get the size of the matrix
[nRows, nCols] = size(heatMapValues);
% Loop through each cell
for row = 1:nRows
for col = 1:nCols
% Add text to the cell with a number as a superscript
text(col, row, sprintf('%s^{%d}', 'x', 4), ...
'HorizontalAlignment', 'center', ...
'Color', 'k');
end
end
3. To add black boundaries to the cells, ‘line’ function can be used. Lines can be drawn on the existing plot, ‘LineWidth’ can be changed to get the boundary of desired thickness. Refer to the following code snippet:
% Add black boundaries
hold on;
for row = 0.5:nRows+0.5
line([0.5, nCols+0.5], [row, row], 'Color', 'k', 'LineWidth', 10);
end
for col = 0.5:nCols+0.5
line([col, col], [0.5, nRows+0.5], 'Color', 'k', 'LineWidth', 10);
end
hold off;
Please refer to the documentation of ‘imagesc’,text’,sprintf’ and ‘line’ for more information:
  1. limagesc”: www.mathworks.com/help/matlab/ref/imagesc.html
  2. “text”: www.mathworks.com/help/matlab/ref/text.html
  3. sprintf”: www.mathworks.com/help/matlab/ref/sprintf.html
  4. line”: www.mathworks.com/help/matlab/ref/line.html
Hope this helps!

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Distribution Plots에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by