How to plot with initially undefined number of lines in a .m file
Show older comments
I am trying to make a general .m file to use for a series of graphs I will need to make - some with 3 lines, some with 2, some with more. Is there a way to code it so that I don't have to use different .m files each time I want to use a different number of variables? for example, the code below has X/Y 1 2 and 3, but can I make it so that it can be used for only 2 x and y data sets, or for more, and still have the correct legend entries for the number of lines present?
function graphPro(X1, Y1, X2, Y2, X3, Y3, legend1, legend2, legend3,xaxis, yaxis, charttitle)
%CREATEFIGURE(X1,Y1,X2,Y2,X3,Y3)
% X1: x-data for 1st detector/energy/field size
% Y1: y-data for 1st detector/energy/field size
% X2: x-data for 2nd detector/energy/field size
% Y2: y-data for 2nd detector/energy/field size
% X3: x-data for 3rd detector/energy/field size
% Y3: y-data for 3rd detector/energy/field size
% legend 1: legend name for x1/y1
% legend 2: legend name for x2/y2
% legend 3: legend name for x3/y3
% xaxis: label and units of x-axis
% yaxis: label and units of y-axis
% charttitle: title of graph
% Create figure
figure1 = figure;
% Create axes
axes1 = axes('Parent',figure1);
hold(axes1,'all');
% Create plot
plot(X1,Y1,'Parent',axes1,'Color',[1 0 0],'DisplayName',legend1,'LineStyle','-');
% Create plot
plot(X2,Y2,'Parent',axes1,'Color',[0 0 1],'DisplayName',legend2,'LineStyle','-');
% Create plot
plot(X3,Y3,'Parent',axes1,'Color',[0 0 0],'DisplayName',legend3,'LineStyle','-');
%Edit space
grid on
% Create xlabel
xlabel(xaxis,'FontSize',10);
% Create ylabel
ylabel(yaxis,'FontSize',10);
% Create title
title(charttitle,'FontSize',14);
% Create legend
legend(axes1,'show','Location','best');
Answers (3)
Sean de Wolski
on 18 May 2011
doc varargin
doc nargin
Use one of the above to determine how many inputs there are, then use a for-loop to create that many figures etc.
Oleg Komarov
on 18 May 2011
0 votes
Yes you can make it dynamic with:
myPlot(X,Y,legend,axis,title)
For say n graphs:
- X,Y are m by n double arrays, or if not of the same length 1 by n cell array containing a series per cell
- legend,axis,title containing all the properties in n cells.
You could then loop for the number of cell and create n graphs.
Megan
on 18 May 2011
0 votes
Categories
Find more on Line 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!