Calculations/Data-Analyzer/+Plotter/plotHeatmap.m

70 lines
2.4 KiB
Matlab

function plotHeatmap(results_all, x_values, y_values, fieldName, varargin)
%% plotHeatmap: Plots a heatmap for a field in a struct array.
%
% Usage:
% plotHeatmap(results_all, x_values, y_values, fieldName, ...
% 'FigNum', 1, 'Colormap', parula, 'CLim', [0 1], ...
% 'XLabel', '\alpha (degrees)', 'YLabel', 'BField (G)', ...
% 'Title', 'My Title', 'SaveFileName', 'heatmap.fig', ...
% 'SaveDirectory', 'results', 'SkipSaveFigures', false);
% --- Parse optional inputs ---
p = inputParser;
addParameter(p, 'FigNum', []);
addParameter(p, 'Colormap', parula);
addParameter(p, 'CLim', []);
addParameter(p, 'XLabel', '\alpha (degrees)');
addParameter(p, 'YLabel', 'BField (G)');
addParameter(p, 'Title', fieldName);
addParameter(p, 'FontName', 'Arial');
addParameter(p, 'FontSize', 14);
addParameter(p, 'SkipSaveFigures', false, @islogical);
addParameter(p, 'SaveFileName', 'heatmap.fig', @ischar);
addParameter(p, 'SaveDirectory', pwd, @ischar);
parse(p, varargin{:});
opts = p.Results;
N_y = length(results_all);
N_x = length(x_values);
% --- Preallocate data matrix ---
data_matrix = NaN(N_y, N_x);
for i = 1:N_y
if isfield(results_all(i), fieldName)
data_matrix(i, :) = results_all(i).(fieldName);
else
warning('Field "%s" does not exist in results_all(%d). Filling with NaN.', fieldName, i);
end
end
% --- Create figure ---
if isempty(opts.FigNum)
fig = figure;
else
fig = figure(opts.FigNum);
end
clf(fig);
set(fig, 'Color', 'w', 'Position', [50 50 950 750]);
% --- Plot heatmap ---
imagesc(x_values, y_values, data_matrix);
colormap(opts.Colormap);
if ~isempty(opts.CLim)
caxis(opts.CLim);
end
set(gca, 'FontName', opts.FontName, 'FontSize', opts.FontSize, 'YDir', 'normal');
% --- Labels and title ---
xlabel(opts.XLabel, 'Interpreter', 'tex', 'FontName', opts.FontName, 'FontSize', opts.FontSize);
ylabel(opts.YLabel, 'Interpreter', 'tex', 'FontName', opts.FontName, 'FontSize', opts.FontSize);
title(opts.Title, 'Interpreter', 'latex', 'FontSize', opts.FontSize + 2, 'FontWeight', 'bold');
colorbar;
% --- Save figure ---
Plotter.saveFigure(fig, ...
'SaveFileName', opts.SaveFileName, ...
'SaveDirectory', opts.SaveDirectory, ...
'SkipSaveFigures', opts.SkipSaveFigures);
end