How plot a messy random-size circles in MATLAB?

1.1k Views Asked by At

I am going to draw a figure such as below picture in the MATLAB R2014b: Messy Circles.

This figure consists of many circles with different (random) colors and random sizes.

How is it possible to plot such this figure in MATLAB R2014b?

2

There are 2 best solutions below

0
On BEST ANSWER

Without spelling out the code:

  1. Pick initial circle, e.g. Position [0,0] and radius 1.
  2. Initialise list for positions and radii.
  3. Pick random position and radius r.
  4. If circle is not in big one (I.e. sqrt(pos(1)^2+pos(2)^2) + r > 1) continue with 3.
  5. If overlap with other circles (distance between positions > sum of radii), continue with 3
  6. Add circle to list, continue with 3

Update: Example

Alright, so I just wanted to try this. I'm sure this is not the best implementation, but:

% set number of circles to plot
n = 200;
radii = zeros(n, 1);
pos = zeros(n, 2);
allColours = lines(n);
% main loop
for idx = 1:n
    is_good = false;
    % generate random positions and radii until we have a hit
    while ~is_good
        pos(idx, :) = rand(1, 2)*2 - 1;
        radii(idx) = rand * (1 - max(radii));
        if ((sqrt(sum(pos(idx, :).^2)) + radii(idx) ) < 1) ... % ensure we're inside the big circle
                && ((idx == 1) || ... %  and either it's the first circle, or
                all(sqrt(sum((pos(1:(idx-1), :) - repmat(pos(idx, :), idx-1, 1)).^2, 2)) > radii(1:(idx-1))+radii(idx))) % all distances are bigger than sum of radii of existing circles
            is_good = true;
        end
    end
end
%% plot
figure(2);
clf;

hold on
set(gca, 'visible', 'off')
daspect([1, 1, 1])
rectangle(...
    'Position',[-1 -1 2 2],...
    'Curvature', [1 1],...
    'FaceColor', 'none',...
    'EdgeColor', [ 0, 0, 0]);
for idx = 1:n
    rectangle(...
        'Position',[pos(idx, 1) - radii(idx), pos(idx, 2) - radii(idx), 2*radii(idx), 2*radii(idx)],...
        'Curvature', [1 1],...
        'EdgeColor','none',...
        'FaceColor', allColours(idx,:));
end

Example output

2
On

The general idea is below. You'll need to modify it to ensure the circle centers and colors are chosen to suit your particular purpose.

% Define parameters
maxAxis = 100;
maxRadius = 10;
nCircles = 20;
% Random centres
xLoc = randi(maxAxis,nCircles);
yLoc = randi(maxAxis,nCircles);
% Random radii
radius = randi(maxRadius,nCircles);
% Random colours
allColours = rand(nCircles,3);
% Transform the data into position = [left bottom width height]
pos = [xLoc(:)-radius(:) yLoc(:)-radius(:) 2*radius(:)*[1 1]];
% Create and format the axes
ha = axes;
hold on;
axis equal;
box on;
set(ha,'XTickLabel',[],'YTickLabel',[]);
% Create the circles (must be done in loop)
for idx = 1:nCircles
    rectangle(...
        'Position',pos(idx,:),...
        'Curvature',[1 1],...
        'FaceColor',allColours(idx,:),...
        'EdgeColor','none');
end

See

>> doc retangle

for more info.