Clear Filters
Clear Filters

Number of digits in heatmap plot except for the value 0

12 views (last 30 days)
I have a 5X5 matrix and want to show the digits up to 3 decimals in the heatmap. However, I don't want to show the digits if the value in the matrix is 0 or almost 0 (like 10^-7). For example, I want to prevent 0 turns int 0.000. How to fix it?
I know you can use the beneath that changes ALL the elements in the matrix, but that is not what I'm looking for.
h.CellLabelFormat = '%.3f'

Answers (1)

Adam Danz
Adam Danz on 6 Sep 2023
Edited: Adam Danz on 7 Sep 2023
Replace near-0s with 0
>I want to show them as value ''0'' and not ''0.000'' and for the non-zero values in matrix I want three decimals.
You could replace the near-zeros with 0s where "near zero" is defined by some threashold as shown below. Then show up to 3 significant digits.
% Create data with near-zeros
data = rand(8)*10;
data(3:5:end) = rand(1,13)*10e-06;
% Replace near-zeros with 0
threshold = 10e-05;
data(abs(data) < threshold) = 0;
% plot results
figure()
h = heatmap(data);
h.CellLabelFormat = '%.3g';
Replace near-0s with NaNs
> I don't want to show the digits if the value in the matrix is 0 or almost 0 (like 10^-7)
You could replace the near-zeros with NaNs where "near zero" is defined by some threashold as shown below. Then show 3 decimal places.
% Replace near-zeros with NaN
threshold = 10e-05;
data(abs(data) < threshold) = NaN;
% plot results
figure()
h = heatmap(data);
h.CellLabelFormat = '%.3f';
  2 Comments
S.
S. on 7 Sep 2023
Edited: S. on 7 Sep 2023
I don't think I was clear enough. I want and need to show the zero or near zero values (due to numerical issues it is not exactly zero), but I want to show them as value ''0'' and not ''0.000'' and for the non-zero values in matrix I want three decimals.
Adam Danz
Adam Danz on 7 Sep 2023
Edited: Adam Danz on 11 Sep 2023
I've updated my answer. The new solution shows 3 significant digits with no trailing zeros ('%.3g'). This isn't exactly what you asked for because it doesn't guarantee that there will be 3 decimal places.

Sign in to comment.

Categories

Find more on Data Distribution Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!