R: How to Draw Circles in Plots (With Examples)


You can use the following methods to draw a circle in a plot in R:

Method 1: Draw Circle Using Base R

library(plotrix)

#create scatter plot
plot(x, y)

#add circle at specific (x, y) coordinates with specific radius
draw.circle(x=3, y=8, radius=.5)

Method 2: Draw Circle Using ggplot2

library(ggplot2)
library(ggforce)

#create scatter plot with circle at specific location with specific radius
ggplot(data = df, aes(x, y)) +
  geom_point() +
  geom_circle(aes(x0=3, y0=8, r=1), inherit.aes=FALSE) +
  coord_fixed()

The following examples shows how to use each method in practice.

Example 1: Draw Circle Using Base R

To draw a circle on a plot in base R, you need to first install and load the plotrix package:

install.packages('plotrix')
library(plotrix)

Next, we can use the draw.circle() function from the plotrix package to add a circle to a scatter plot in base R:

#create data frame
df <- data.frame(x=c(1, 2, 2, 3, 3, 4, 8),
                 y=c(2, 4, 5, 4, 7, 9, 10))

#create scatter plot
plot(df$x, df$y)

#add circle
draw.circle(x=3, y=8, radius=.5)

You can also use the draw.circle() function multiple times to plot multiple circles on the same plot:

#create data frame
df <- data.frame(x=c(1, 2, 2, 3, 3, 4, 8),
                 y=c(2, 4, 5, 4, 7, 9, 10))

#create scatter plot
plot(df$x, df$y)

#add multiple circles to plot
draw.circle(x=3, y=8, radius=.5)
draw.circle(x=4, y=5, radius=.5, border='red', col='lightblue', lwd=5, lty='dashed')

draw circle in plot in R

Notice that multiple circles have been added to the plot at the (x, y) coordinates that we specified.

Example 2: Draw Circle Using ggplot2

To draw a circle on a plot in ggplot2, you need to first install and load the ggplot2 and ggforce packages:

install.packages('ggplot2')
install.packages('ggforce')
library(ggplot2)
library(ggforce)

Next, we can use the geom_circle() function from the ggforce package to add a circle to a scatter plot in ggplot2:

#create data frame
df <- data.frame(x=c(1, 2, 2, 3, 3, 4, 8),
                 y=c(2, 4, 5, 4, 7, 9, 10))

#create scatter plot with circle
ggplot(data = df, aes(x, y)) +
  geom_point() +
  geom_circle(aes(x0=3, y0=8, r=1), linetype='dashed', color='red',
              fill='lightblue', lwd=1.5, inherit.aes=FALSE) +
  coord_fixed()

draw circle in ggplot2

The circle is placed in the exact (x, y) coordinates that we specified.

Note: If you don’t use the coord_fixed() argument, the circle may appear as an ellipse instead.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Create a Scatterplot in R with Multiple Variables
How to Label Points on a Scatterplot in R
How to Add a Regression Equation to a Plot in R

Leave a Reply

Your email address will not be published.