Clear Filters
Clear Filters

Naming several saveas plots based on user input

4 views (last 30 days)
I am writing a code that takes a user input for an excel file and then makes several plots based off of that input. Each plot is then saved using the saveas function. Is there a way to name the .jpg based on the excel file input as well as the name of the figure? I am creating 7 plots per excel sheet and am unsure how to clearly save the files.

Answers (1)

Jaswanth
Jaswanth on 9 May 2024
Hi Isabelle,
To dynamically name your .jpg files based on the Excel file inputs provided by the user along with a distinct identifier for each figure, one possible approach is by setting up a naming convention for the plots, and generating and saving each plot with a name that reflects its source and type. Kindly refer to the following steps explaining implementation with code snippets of an example for clarity.
Establish Naming Convention: After loading the data from excel file, identify each plot type (Histogram, ScatterPlot, LineGraph) and extract the base name from your Excel file. This base name will be part of the file name for each saved plot. Three plot types have been considered for this example.
plotTypes = {'Histogram', 'ScatterPlot', 'LineGraph'};
[~, baseName, ~] = fileparts(excelFileName);
Create and Save Plots: Iterate through the plot types, generate each plot with MATLAB plotting functions, and construct a file name using the base name of the Excel file and the plot type. Save each plot accordingly.
for i = 1:length(plotTypes)
figure;
switch plotTypes{i}
case 'Histogram'
histogram(data(:,1));
title('Histogram of Column 1');
case 'ScatterPlot'
scatter(data(:,1), data(:,2));
title('Scatter Plot of Columns 1 and 2');
case 'LineGraph'
plot(data(:,1), data(:,2));
title('Line Graph of Columns 1 and 2');
otherwise
disp('Unknown plot type');
end
figureName = sprintf('%s_%s.jpg', baseName, plotTypes{i});
saveas(gcf, figureName);
close(gcf);
end
Please refer to MathWorks documentation to know further details on switch, case, otherwise syntax functions used in the example above: https://www.mathworks.com/help/matlab/ref/switch.html?searchHighlight=switch%20case&s_tid=srchtitle_support_results_1_switch%20case
I hope the information provided above is helpful in accomplishing your task.

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!