Open In App

Draw a Polygon between specified points in R Programming – polygon() Function

Last Updated : 17 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

polygon() function in R Language is used to plot a polygon between specified points in an existing plot.

Syntax: polygon(x_coordinates, y_coordinates)

Parameters :
x_coordinates, y_coordinates: x, y coordinates of plot to draw polygon Returns: a polygon in a given plot

Example 1: Draw a 4 Sided Polygon in an R Plot 

R
# Draw an empty plot
plot(2, 2, col = "white", xlab = "X", ylab = "Y")  

# Draw a polygon
polygon(x = c(2.7, 2.3, 2.2, 2.8), 
        y = c(2.6, 2.8, 2.4, 2),  
        col = "darkgreen") 

Output:

4-sided-polygon-in-r

A 4-sided polygon

Example 2: Color borders of polygon 

Here, border specifies the border color and lwd specifies the border thickness.

R
# Draw empty plot
plot(2, 2, col = "white", xlab = "X", ylab = "Y") 

# Draw a polygon
polygon(x = c(2.7, 2.3, 2.2, 2.8), 
        y = c(2.6, 2.8, 2.4, 2),   
        col = "darkgreen",          
        border = "red",            
        lwd = 8)          # Thickness of border

Output: colour-borders-polygon-r

Example 3: Draw frequency polygon 

R
x1 <- 1:10                          
y1 <- c(2, 4, 7, 4, 5, 8, 6, 6, 1, 2)  

plot(x1, y1,                                       
     type = "l",     # Set line type to line
     lwd = 4)         # Thickness of line
     
# X-Y-Coordinates of polygon
polygon(c(1, x1, 10), c(0, y1, 0),          
        col = "darkgreen")  

# Add squares to frequency polygon
points(x1, y1,                          
       cex = 1,    # Size of squares                             
       pch = 12)  
       segments(x1, 0, x1, y1)  

Output: frequency-polygonExample 4: Draw polygon below density

In this example we will make Probability density function. 

R
set.seed(15000)      
N <- 1000             

# Draw random poisson distribution
x1 <- rpois(N, 2)    

plot(density(x1),  # Draw density plot
     main = "",    
     xlab = "x1")   
     
# X-Coordinates of polygon
polygon(c(min(density(x1)$x), density(x1)$x),           
        c(0, density(x1)$y),     # Y-Coordinates of polygon
        col = "darkgreen")       

Output: polygon-below-density

Example 5 : Creating a polygon using coordinates

R
# Define the x and y coordinates of the polygon vertices
x <- c(1, 3, 4, 2)
y <- c(1, 2, 4, 3)

# Plot the polygon
plot(x, y, type = "n") # type = "n" to create an empty plot
polygon(x, y, col = "blue")

Output :

A ploygon with given x,y vertices



Next Article
Article Tags :

Similar Reads