MATLAB:如何改变已加载图形的线条属性?

15

对于MATLAB用户,我有一个非常简单的问题:

如果我使用load命令加载一个图形文件(.fig),是否有办法从命令行更改绘制线条的属性?(宽度、颜色、标记等)

注:根据定义用于绘图线条颜色页面中的信息,前两个选项只适用于使用plot命令。显然,如果您加载了图形,则这些选项无效。

4个回答

18

您可以使用FINDOBJ函数获取当前图形上所有线对象的句柄:

hline = findobj(gcf, 'type', 'line');

然后你可以更改所有线对象的某些属性:

set(hline,'LineWidth',3)

或者只是其中的一些:

set(hline(1),'LineWidth',3) 
set(hline(2:3),'LineStyle',':') 
idx = [4 5];
set(hline(idx),'Marker','*') 

2
为了操作图中的对象,您需要访问它们的手柄。如果您使用绘图函数创建图形,则会返回这些手柄。在打开图形时,您需要遵循图形对象树以查找要操作的特定元素的句柄,这也是您的情况。 此页面包含有关图形对象结构的信息。
要访问所需的手柄路径将取决于您的图形,但是,例如,如果您使用简单的plot命令创建了图形,则可以通过以下方式更改线条属性:
x = 0:0.1:2;
plot(x,sin(x));

fig = gcf % get a handle to the current figure
% get handles to the children of that figure: the axes in this case
ax = get(fig,'children') 
% get handles to the elements in the axes: a single line plot here
h = get(ax,'children') 
% manipulate desired properties of the line, e.g. line width
set(h,'LineWidth',3)

谢谢提供的信息。我会考虑的。不过,我觉得上面的替代方案更直观。 - aarelovich

2
除了 @yuk 的回答之外,如果您还有一个绘制为图例的话,
hline = findobj(gcf, 'type', 'line');

将返回N x 3行(或更精确地说- 绘制的行数+ 2x图例中的行数)。我这里只考虑所有绘制的行也都在图例中的情况。

顺序很奇怪: 如果绘制了5条线(我们将它们标记为1到5),并添加了图例,则会出现以下情况:

hline:
1 : 5 th line (mistical)    
2 : 5 th line (in legend)
3 : 4 th line (mistical)    
4 : 4 th line (in legend)
5 : 3 th line (mistical)    
6 : 3 th line (in legend)
7 : 2 th line (mistical)    
8 : 2 th line (in legend)
9 : 1 th line (mistical)    
10: 1 th line (in legend)
11: 5 th line (in plot)
12: 4 th line (in plot)
13: 3 th line (in plot)
14: 2 th line (in plot)
15: 1 th line (in plot)

作为一个解决方案(周五晚上拖延),我做了这个小宝贝:

解决方案1:如果你不想重置图例

检测是否有图例以及绘制了多少条线:

hline = findobj(gcf, 'type', 'line');
isThereLegend=(~isempty(findobj(gcf,'Type','axes','Tag','legend')))

if(isThereLegend)
    nLines=length(hline)/3
else
    nLines=length(hline)
end

针对每一行找到正确的句柄并执行该行的操作(同样适用于相应的图例行)。
for iterLine=1:nLines
    mInd=nLines-iterLine+1
    if(isThereLegend)
        set(hline([(mInd*2-1) (mInd*2) (2*nLines+mInd)]),'LineWidth',iterLine) 
    else
    set(hline(mInd),'LineWidth',iterLine)     
    end
end

这使得每个宽度为i的行都带有i-th,在这里可以添加自动属性更改; 解决方案2:保持简单
摆脱图例,注意线条,重置图例。
legend off
hline = findobj(gcf, 'type', 'line');
nLines=length(hline)

for iterLine=1:nLines
    mInd=nLines-iterLine+1
    set(hline(mInd),'LineWidth',iterLine)     
end
legend show

当传说必须放置在某个特定位置等情况下,这可能不合适。


0

您也可以在查看器中右键单击该行,并在那里更改属性。这也会更改相应的“图例”条目(至少在2014b中是这样)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接