如何指定网格线颜色Matlab

时间:2017-04-09 16:54:52

标签: matlab grid matlab-figure

我想在Matlab中使用Meshgrid显示一个网格,并指定颜色(或任何不同的方法),我的代码是:

figure(1)
X = [-1:0.5:1];
Y= [-1:0.5:1];
[X,Y] = meshgrid(X,Y)
plot(X,Y,'k-')
hold on
plot(Y,X,'k-');

此代码显示所有黑色线条,但我想显示一些不同颜色的线条:

figure(1)
X = [-1:0.5:1]; % with black color
X = [-1:0.2:1]; % with red color
Y= [-1:0.5:1]; % with black color
Y= [-1:0.2:1]; % with red color

怎么做?

2 个答案:

答案 0 :(得分:1)

在调用plot时使用不同的颜色规范:

X = [-1:0.5:1]; % with black color
x = [-1:0.2:1]; % with red color
Y= [-1:0.5:1]; % with black color
y= [-1:0.2:1]; % with red color

[X,Y] = meshgrid(X,Y);
[x,y] = meshgrid(x,y);
plot(X,Y,'k-','Linewidth',2)
hold on
plot(Y,X,'k-','Linewidth',2);
plot(x,y,'r-');
plot(y,x,'r-');

enter image description here

答案 1 :(得分:0)

另一种方法是使用内置网格:

h=gca;
grid on    % turn on major grid lines
grid minor % turn on minor grid lines
% Set limits and grid spacing separately for the two directions:
h.XAxis.Limits=[-1,1];
h.XAxis.TickValues=-1:0.5:1;
h.XAxis.MinorTickValues=-1:0.2:1;
h.YAxis.Limits=[-1,1];
h.YAxis.TickValues=-1:0.5:1;
h.YAxis.MinorTickValues=-1:0.2:1;
% Must set major grid line properties for both directions simultaneously:
h.GridLineStyle='-'; % the default is some dotted pattern, I prefer solid
h.GridAlpha=1;  % the default is partially transparent
h.GridColor=[0,0,0]; % here's the color for the major grid lines
% Idem for minor grid line properties:
h.MinorGridLineStyle='-';
h.MinorGridAlpha=1;
h.MinorGridColor=[1,0,0]; % here's the color for the minor grid lines

请注意,您可以通过一次设置多个属性来缩短上述代码:

h=gca;
grid on
grid minor
set(h.XAxis,'Limits',[-1,1],'TickValues',-1:0.5:1,'MinorTickValues',-1:0.2:1)
set(h.YAxis,'Limits',[-1,1],'TickValues',-1:0.5:1,'MinorTickValues',-1:0.2:1)
set(h,'GridLineStyle','-','GridAlpha',1,'GridColor',[0,0,0])
set(h,'MinorGridLineStyle','-','MinorGridAlpha',1,'MinorGridColor',[1,0,0])