• Category
  • >R Programming

Customizing Your Visuals with ggplot2 in R Programming: Part 2

  • Lalit Salunkhe
  • Jan 22, 2021
Customizing Your Visuals with ggplot2 in R Programming: Part 2 title banner

In our previous article, we have tried to give you a glimpse of ggplot2 (grammar of graphics using ggplot2) and the way you can customize your visuals such as customizing titles, axes labels, customizing themes, combining two visuals together, etc. using ggplot2. 

 

Through this article, we will move forward with the same and get you some more customizations in terms of colours, annotations, legends, etc. in your visuals using ggplot2. 

 

Before that, if you haven’t read our previous article on this trail, you can see it here, customizing visuals with ggplot2 in R programming. If you ask me personally, I will recommend you to read that one and then come towards this one as this blog is the successor of the previous one. 


 

Customizing Legends

 

Legends are by default used to be placed at the margins of the whole graph; if your graph has data and visualization that supports/requires the legend. However, you can change the position of the legend if you use the theme() function in combination with the legend. position(). Let us create a scatter plot in a way that generates the legends.


library(ggplot2)

#Accessing the mpg dataset from ggpplot2

data <- ggplot2::mpg

ggplot(data)+

  aes(x = displ, y = hwy)+

#Creatig a scatter plot

  geom_point()+

  aes(color = class)

Here, in this example, we have created a scatter plot with colour-coding associated with the class variable. See the output as shown below:


This image shows the scatter plot with legends

Scatter plot with default legends


To customize the position of the legend, we need to use the theme() function with the legend. position(). See the code below which illustrates it.


library(ggplot2)

#Accessing the mpg dataset from ggpplot2

data <- ggplot2::mpg

ggplot(data)+

  aes(x = displ, y = hwy)+

#Creatig a scatter plot

  geom_point()+

  aes(color = class)+

  theme(legend.position = "bottom") #Legends at the bottom side

 


 

Here, the legend.position() allows you to set the position of the legend which as of now is at the bottom, but can be changed to top, left, or right. See the output as shown below:


This image shows the output of the code where the position of the legend is customized.

Customizing the legend position


We can also change the title of the legends with help of the lab() function. Just make sure you are adding the same argument which is added as a classifier in the aesthetic (in this case, colour = ).


library(ggplot2)

#Accessing the mpg dataset from ggpplot2

data <- ggplot2::mpg

ggplot(data)+

  aes(x = displ, y = hwy)+

#Creatig a scatter plot

  geom_point()+

  aes(color = class)+

  labs(color = "Class of the cars")+    #Changing the title of legend

  theme(legend.position = "top") #Legends at the top

Here, the lab function has the same argument as that of the aes() classifier. And the title of the legend is changed to “Class of the cars”. Moreover, the position of the legend is changed to “top” rather than “bottom” as it was previously. See the output as shown below:


labs() function allows you to customize the title of the legend.

Customizing the legend title with labs()


(Also read: Packages in R Programming)

 

 

Customizing Text and Labels

 

To customize the text and labels in R programming, we can use the geom_text() and annotate() functions under the ggplot2. Well, these functions can be used in combination with aes() function in order to achieve the desired results.

 

When we talk about customizing the text, we usually are considering adding the text labels to each of the points on the graph. To achieve this, see the code as shown below which has the geom_text() function used in combination with aes() to achieve the desired result.


library(ggplot2)

#Accessing the mpg dataset from ggpplot2

data <- ggplot2::mpg

ggplot(data)+

  aes(x = displ, y = hwy)+

  #Creatig a scatter plot

  geom_point()+

  #Customizing the text for each point on scatterplot

  geom_text(aes(label = rownames(data)),   

            check_overlap = TRUE,

            size = 3,

            vjust = "top",

            hjust = "top"

            )

Here, the geom_text() in combination with aes() function and some additional arguments where check_overlap defines whether the text is overlapping or not, if this argument is set to TRUE, all the text overlapping first text in the line will be neglected. 

 

The size argument specifies the text size, as usual, and also the vjust and hjust arguments are there to specify the text alignments vertically and horizontally respectively. Values for them could either be text such as “top”, “bottom”, “middle” etc., or respective numbers in between 0 and 1.

 

The graph should look as shown in the screenshot below:


This image shows how the text labels can be added to the row points for the given scatterplot.

Adding text and labels to the scatter points


To customize and add the text label on graph, we can use the annotate() function. This will allow us to add the labels on graph side based on the axes position. See the code as shown below:


library(ggplot2)

#Accessing the mpg dataset from ggpplot2

data <- ggplot2::mpg

ggplot(data)+

  aes(x = displ, y = hwy)+

  #Creatig a scatter plot

  geom_point()+

  #Customizing the text for each point on scatterplot

  geom_text(aes(label = rownames(data)),   

            check_overlap = FALSE,

            size = 3,

            vjust = "top",

            hjust = "top"

            ) +

  #Adding text label on the graph side

  annotate("text", 

           x = 6, 

           y = 35, 

           label = "hwy and dspl variables \n are negatively correlated",

           size = 5)

 


Here, the annotate() function is used to add the “text”, with positions on x-axis and y-axis with label function allowing to add the text and size function allowing to increase or decrease the size of text we are adding.


This image shows how to add the text label on the graph area with the help of the annotate() function and arguments associated with it.

Adding the label as a text on the graph area


Customizing Graphs With The Facets

 

The best thing about ggplot2 and R programming is that we can have multi-windowed graphs. To achieve this, faceting will help you. Facets allow you to create multi-windowed graphs under R. This will also allow you to customize the facets altogether.

 

The facet_grid() function allows you to create the multi-paned graph in R programming using ggplot2.


library(ggplot2)

#Accessing the mpg dataset from ggpplot2

data <- ggplot2::mpg

ggplot(data)+

  aes(x = displ, y = hwy)+

  #Creatig a scatter plot

  geom_point()+

  #Use facets_grid() function to create a multi-windowed graph

  facet_grid(drv ~ .)

Here, the facet_grid() function is used to create a multi-penned graphical layout which has the normal scatter plot of displ over hwy is being multi-windowed with the variable values associated with levels of drv variables. See the screenshot below:


Using facet_grid() to create multi-penned graph in R programming

Facet_grid() allows you to create multi-windowed graphs


You can also use two variables altogether with the original graph to get the multi-window graphs. See the code below which allows you to create multi-window graph with two variables.


library(ggplot2)

#Accessing the mpg dataset from ggpplot2

data <- ggplot2::mpg

ggplot(data)+

  aes(x = displ, y = hwy)+

  #Creatig a scatter plot

  geom_point()+

  #creating multi-window graph with two variables

  facet_grid(year ~ drv)

Here, in this example, the year variable is marked on the x-scale and drv variable marked on the y-scale in combination with the original graph which is generated for dspl over hwy. See the screenshot below:


Multi-variable faceting in R-Programming under ggplot2 with two variables year and drv.

Faceting with two variables year and drv


Saving Graphs Manually Under ggplot2

 

In order to save the graph under R-Programming, we have ggsave() function. This function usually allows you to save the graph on current working directly unless and otherwise, you have specified a separate location to store the visual.

See the code below, which allows you to save the graph as a pdf at the current working directory.


library(ggplot2)

#Accessing the mpg dataset from ggpplot2

data <- ggplot2::mpg

ggplot(data)+

  aes(x = displ, y = hwy)+

  #Creatig a scatter plot

  geom_point()

#Saving a visual as pdf at current working directory

ggsave("ScatterPlot.pdf")

This code will save the graph as a pdf file named ScatterPlot. Remember, to access the working directory, you can always use the getwd() function. This function will return the current working directory.

 

See the screenshot below where you can see the file saved on the folder.


The file stored as a pdf file on the current working directory.

Storing visuals at the working directory


Summary

 

This article keeps focusing on the how-to customize your visuals with the help of the ggplot2 package.

 

  • Customizing Legends includes the theme() function, labs(), legend.position() etc to customize the legends we are adding into the graph. We can also change the colours.

  • To customize the text and labels, we can use the geom_text() and annotate() functions which allow you to add the labels to row points and to add text on the graph area.

  • Facets will allow you to create the multi-window visuals under R programming. The facet_grid() function particularly helps you create a grid of graph.

  • To save the graph manually to the working directory, we can use the ggsave() function. This function saves the graph on a current working directory or any specified path in allowed formats.

 

Latest Comments

  • Veronica Larry

    May 23, 2022

    I am Veronica Larry From New York.. i want to use this medium to testify how i got cured by Dr Kachi...I was diagnosed with HIV/AIDS disease, and i have been leaving with it since then, but i kept praying and doing everything possible to get cured, so i never stopped doing research about finding a cure...i came across testimonies about people getting cured through herbal medicine, and i have always believe in herbs and roots its medical preparing, after doing so many research about it i found Dr Kachi and i discovered he was a professional in herbs cured and he has also helped many people to got cured, i contacted Dr Kachi and talked on phone and i confirmed he was genuine herbalist, I asked him for solutions and he started the remedies for my health. Thank been to God, I'm now here to testify and overwhelmed when the doctor confirmed me HIV negative in the same hospital i have been before, i wish to anyone that is sick today and want healing please email: drkachispellcast@gmail.com OR WhatsApp number: +1 (570) 775-3362 visit his Website, https://drkachispellcast.wixsite.com/my-site

  • brenwright30

    May 11, 2024

    THIS IS HOW YOU CAN RECOVER YOUR LOST CRYPTO? Are you a victim of Investment, BTC, Forex, NFT, Credit card, etc Scam? Do you want to investigate a cheating spouse? Do you desire credit repair (all bureaus)? Contact Hacker Steve (Funds Recovery agent) asap to get started. He specializes in all cases of ethical hacking, cryptocurrency, fake investment schemes, recovery scam, credit repair, stolen account, etc. Stay safe out there! Hackersteve911@gmail.com https://hackersteve.great-site.net/