How to add Circles in Plots in R with Examples

How to add Circles in Plots in R?. To draw a circle in a plot in R, use the following methods.

Approach 1: Using Base R, draw a circle.

library(plotrix)

Syntax for creating scatter plot

plot(x, y)

Now we can add circles at specific (x, y) coordinates with specific radius

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

Approach 2: ggplot2 is used to draw a circle.

library(ggplot2)
library(ggforce)

make a scatter plot with a circle at a given position and radius

ggplot(data = df, aes(x, y)) +
  geom_point() +
  geom_circle(aes(x0=3, y0=8, r=1), inherit.aes=FALSE) +
  coord_fixed()

The examples below demonstrate how to apply each strategy in practice.

Example 1: Using Base R, draw a circle

You must first install and load the plotrix package in order to create a circle on a plot in R:

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

To add a circle to a scatter plot in base R, we can use the plotrix package’s draw.circle() function.

create a data frame

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

create a scatter plot

plot(df$x, df$y)

Now add circle

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

You can also use the draw to your advantage. To plot many circles on the same plot, use the circle() function multiple times.

Let’s create a data frame

df <- data.frame(x=c(2, 3, 4, 3, 4, 5, 6),
                 y=c(6, 3, 5, 2, 8, 11, 10))

As usual, we can create a scatter plot

plot(df$x, df$y)

Now add multiple circles to the plot

draw.circle(x=3, y=8, radius=.5)
draw.circle(x=4, y=5, radius=.5, border='blue', col='red', lwd=5, lty='dashed')

At the (x, y) coordinates that we supplied, many circles have been placed on the plot.

Best Data Science Books For Beginners » finnstats

Example 2: Draw Circle Using ggplot2

Install and load the ggplot2 and ggforce packages before drawing a circle on a plot in ggplot2.

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

Next, we can use the ggforce package’s geom circle() function to add a circle to a scatter plot in ggplot2.

Let’s create a data frame

df <- data.frame(x=c(2, 3, 4, 3, 4, 5, 6),
                 y=c(6, 3, 5, 2, 8, 11, 10))

Now create a scatter plot with a circle

ggplot(data = df, aes(x, y)) +
  geom_point() +
  geom_circle(aes(x0=3, y0=8, r=1), linetype='dashed', color='red',
              fill='blue', lwd=1.5, inherit.aes=FALSE) +
  coord_fixed()

The circle is centered on the (x, y) coordinates we gave.

Note that if you don’t use the coord fixed() parameter, the circle can end up looking like an ellipse.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

twenty − 15 =