我有一个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;
输出是一个圆圈:
现在,我想用不同的颜色着色这些圆圈。我无法解决这个问题。我感谢我对简单代码的贡献。
答案 0 :(得分:3)
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;
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;
答案 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