How can I make these few lines a function?

1 次查看(过去 30 天)
Hi all!
When I am plotting any graph (even for the individual subplot), I add these few lines everytime.
set(gca,'color',[1 1 1]);
set(gcf,'Position',[-2237,65,2084,1272],'Resize','on');
box on;
set(findall(gcf,'-property','LineWidth'),'LineWidth',2);
hold on;
a = get(gca,'XTickLabel');
set(gca,'XTickLabel',a,'fontsize',16,'FontWeight', 'bold');
b = get(gca,'YTickLabel');
set(gca,'YTickLabel',b,'fontsize',16,'FontWeight', 'bold');
set(gca, 'Layer', 'top')
Of course, I write these lines to make my plot look better. But say, when I plot 10 plots, I have to write the same lines 10 times which makes my code look unnecessarily large. Is there anyway to make a function using these few lines so that I don't have to write them repeatedly?
Any response from you will be highly appreciated!

采纳的回答

David Hill
David Hill 2022-8-16
function graphSetup()
set(gca,'color',[1 1 1]);
set(gcf,'Position',[-2237,65,2084,1272],'Resize','on');
box on;
set(findall(gcf,'-property','LineWidth'),'LineWidth',2);
hold on;
a = get(gca,'XTickLabel');
set(gca,'XTickLabel',a,'fontsize',16,'FontWeight', 'bold');
b = get(gca,'YTickLabel');
set(gca,'YTickLabel',b,'fontsize',16,'FontWeight', 'bold');
set(gca, 'Layer', 'top')
end
  1 个评论
Ashfaq Ahmed
Ashfaq Ahmed 2022-8-16
编辑:Ashfaq Ahmed 2022-8-16
Thank you! It was straight forward! Should have thought this way haha.

请先登录,再进行评论。

更多回答(2 个)

Walter Roberson
Walter Roberson 2022-8-16
Sure, just toss them in a function and call the function.
I might suggest, though,
function setup_plots(ax)
if nargin < 1; ax = gca; end
fig = ancestor(ax, 'figure');
set(ax,'color',[1 1 1]);
set(fig,'Position',[-2237,65,2084,1272],'Resize','on');
box(ax, 'on');
set(findall(fig,'-property','LineWidth'),'LineWidth',2);
hold(ax, 'on');
a = get(ax,'XTickLabel');
set(ax,'XTickLabel',a,'fontsize',16,'FontWeight', 'bold');
b = get(ax,'YTickLabel');
set(ax,'YTickLabel',b,'fontsize',16,'FontWeight', 'bold');
set(ax, 'Layer', 'top');
end
This would give you the option of passing in a particular axes handle to set up. For example,
ax = subplot(5,7, 2);
setup_plots(ax)
It is always more robust to be explicit about which axes you are dealing with, as otherwise there are various ways in which the "active"axes can change, even in the middle of executing a function.
  1 个评论
Ashfaq Ahmed
Ashfaq Ahmed 2022-8-16
Wonderful! Thanks a lot Walter!! I have received so many great answers from you already!! You are very kind.

请先登录,再进行评论。


Steven Lord
Steven Lord 2022-8-16
If you want all the axes you create going forward to have those property values, consider changing the default property values rather than running a function to change them after the fact.

类别

Help CenterFile Exchange 中查找有关 2-D and 3-D Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by