recipes : Plotting : Line and Scatter Plots : How do I plot a circle?


How do I plot a circle?


Here are two ways of doing it. In the first example the circle is plotted using a line (the same way that any line graph would be plotted). This approach can't produce a filled circle.

numPoints=100; %Number of points making up the circle
radius=1;      %Radius of the circle

%Define circle in polar coordinates (angle and radius)
theta=linspace(0,2*pi,numPoints); %100 evenly spaced points between 0 and 2pi
rho=ones(1,numPoints)*radius; %Radius should be 1 for all 100 points

%Convert polar coordinates to Cartesian for plotting
[X,Y] = pol2cart(theta,rho); 

%Plot a red circle
axis square

%Altering the radius allows us to plot a second circle within the first one
[X,Y] = pol2cart(theta,rho);
hold on
hold off

We can fill the black circle we just made using the patch command

H=patch(X,Y,1); %Make a patch object
set(H,'FaceColor',[1,1,1]*0.5) %Set the color to grey


The key is the command pol2cart. The circle is defined in polar coordinates with theta being the angles 0 to 360 defined in radians (most Matlab functions expect angles to be specified in radians). rho is the radias associated with each angle. Since we're plotting a circle rather than an elipse, all values of rho must be identical. pol2cart converts these values into Cartesian (x and y) coordinates, which are suitable for use with the plotting tools. You may also be interested in the related recipe: plotting a spiral.