如何在MATLAB中为一个图中的圆圈着色?

时间:2015-06-13 21:04:40

标签: matlab graphics plot matlab-figure

我有一个MATLAB代码如下:

MinVal = -1;
MaxVal = 1;
MaxRadius = 0.5;
nCircles = 5;
Dimension = 2;
Circles = zeros(nCircles, Dimension);
Radius = zeros(nCircles, 1);

for i = 1 : nCircles
Circles(i,:) = unifrnd(MinVal, MaxVal, [1, Dimension]);
Radius(i) = unifrnd(0, MaxRadius, 1);
end

t = 0 : .1 : 2 * pi;

figure;
hold on;
for i = 1 : nCircles
x = Radius(i) * cos(t) + Circles(i,1);
y = Radius(i) * sin(t) + Circles(i,2);
plot(x,y);
end

axis square;
grid on;

输出是一个圆圈:

enter image description here

现在,我想用不同的颜色着色这些圆圈。我无法解决这个问题。我感谢我对简单代码的贡献。

2 个答案:

答案 0 :(得分:3)

方法1:使用rectangle,纯色。可能会覆盖一些圈子

绘制圆圈的最简单(尽管不是很直观)方法是使用rectangle函数,'curvature'属性设置为[1 1]。要填充圆圈,请通过'facecolor'属性指定颜色。圆边框的颜色由'edgecolor'属性控制。

由于圆圈是彩色的,您可能会将其中一些部分或完全覆盖在其他圆圈中。

代码中的修改行标有注释。

MinVal = -1;
MaxVal = 1;
MaxRadius = 0.5;
nCircles = 5;
Dimension = 2;
Circles = zeros(nCircles, Dimension);
Radius = zeros(nCircles, 1);
cmap = hsv(nCircles); %// define colors. You could change `hsv` to `jet`, `cool`, ...

for i = 1 : nCircles
    Circles(i,:) = unifrnd(MinVal, MaxVal, [1, Dimension]);
    Radius(i) = unifrnd(0, MaxRadius, 1);
end

figure;
hold on;
for i = 1 : nCircles
    rectangle('Curvature', [1 1], ...
        'Position', [Circles(i,:)-Radius(i) repmat(2*Radius(i),1,2)], ...
        'facecolor', cmap(i,:), 'edgecolor', 'none') %// plot filled circle
end

axis equal; %// same aspect ratio in both axes
grid on;

enter image description here

方法2:使用patch透明色。覆盖的圆圈是可见的

要使圆圈可见,即使它们已被遮盖,您也可以使用具有透明度(alpha)的颜色。 rectangle不支持透明度,因此您必须使用patch函数。代码基本上与您的代码类似,将plot替换为patch,并通过相应的属性指定颜色和透明度。

MinVal = -1;
MaxVal = 1;
MaxRadius = 0.5;
nCircles = 5;
Dimension = 2;
Circles = zeros(nCircles, Dimension);
Radius = zeros(nCircles, 1);
cmap = hsv(nCircles); %// define colors. You could change `hsv` to `jet`, `cool`, ...
alpha = .5; %// define level of transparency

for i = 1 : nCircles
    Circles(i,:) = unifrnd(MinVal, MaxVal, [1, Dimension]);
    Radius(i) = unifrnd(0, MaxRadius, 1);
end

t = 0 : .1 : 2 * pi;

figure;
hold on;
for i = 1 : nCircles
    x = Radius(i) * cos(t) + Circles(i,1);
    y = Radius(i) * sin(t) + Circles(i,2);
    patch(x, y, 'none', 'facecolor', cmap(i,:), 'facealpha', alpha, ...
        'edgecolor', 'none'); %// plot filled circle with transparency
end

axis equal; %// same aspect ratio in both axes
grid on;

enter image description here

答案 1 :(得分:1)

@Luis的回答是针对填充颜色的圆圈。我在问题中添加了一个答案,仅用于边缘颜色。

您可以按照所需的顺序指定所需的颜色,然后将其作为参数添加到plot命令中:

figure;
colors={'k','b','r','g','y','c'};
for i = 1 : nCircles
   x = Radius(i) * cos(t) + Circles(i,1);
   y = Radius(i) * sin(t) + Circles(i,2);
   hold on;
   plot(x,y,colors{i});
end