Open In App

Add Panel Border to ggplot2 Plot in R

In this article, we will use theme() function to add panel border to the plot in R Programming Language. Here we will create a scatter plot, but you can apply it to any plot and add a Panel Border to that one.

Approach:

Syntax: theme(panel.border) 



Parameter: theme() has many parameters to specify the theme of plot. we can use them as per our requirements but for add panel border to plot, we will use only panel.border parameter and specify element_rect() function as it’s value.

Return: Theme of the plot. 



element_rect() is used for specifying borders and backgrounds.

Syntax:

element_rect(color = “color_name”, fill = NULL, size = NULL, linetype = NULL) 

Parameter: 

  • fill : Specifies the color by which we fill whole rectangle.
  • color : For specifying border color.
  • size : For specifying border size.
  • linetype : For specifying border line type

Return: Border around plot.

Dataset in use:

  year point
1 2011 10
2 2012 20
3 2013 30
4 2014 40
5 2015 50

Let just first create a regular scatter plot to understand the difference better.

Example:




# load ggplot2 package
library(ggplot2)
  
# Create a dataframe for Plot data
data <- data.frame(year = c(2011, 2012, 2013, 2014, 2015),
                   point = c(10, 20, 30, 40, 50))
  
# Plot the scatter plot
ggplot(data, aes(year, point)) +    
  geom_point()+
  ggtitle("Scatter Plot")

Output:

Simple Scatter plot using ggplot2

Now let’s add a border to it and display the result.

Example:




# load ggplot2 package
library(ggplot2)
  
# Create a dataframe for Plot data
data <- data.frame(year = c(2011, 2012, 2013, 2014, 2015),
                   point = c(10, 20, 30, 40, 50))
  
# Plot the scatter plot with panel border
# of size 10 and green color
ggplot(data, aes(year, point)) +    
  geom_point()+
  ggtitle("Scatter Plot with Panel Border")+
  theme(panel.border = element_rect(color = "green",
                                    fill = NA,
                                    size = 10))

Output: 

Scatter Plot with Panel Border


Article Tags :