Draw ggplot2 plot with two Y-axes on each side and different scales in R
Last Updated :
24 Jun, 2021
There are many data available that have more than one unit like Temperature, Pressure, Height of a person, etc. We want to represent these data using more than one unit in a basic plot because other users may not be familiarized with the unit you have provided in the plot. It becomes difficult for them to analyze from the plot. In such a case, we need two axes having different scales on both. Therefore, dual axes can be used if there is scaling between both axes. This is known as a scaling factor.
For example, One y-axis can have distance in miles and another ax can have distance in kilometer because there might be a few people who are not comfortable with measuring distances using miles.
In this article, we are going to see how to add two vertical axes on either side having different scales using the ggplot2 bar plot in R Programming Language using a suitable example.
Installation
First, you need to install the ggplot2 package if it is not previously installed in R Studio. To install and load write the below command in R Console :
install.packages("ggplot2")
library(ggplot2)
Creating Bar Plot
For creating a simple bar plot we will use the function geom_bar( ).
Syntax: geom_bar(stat, fill, color, width)
Parameters :
- stat : Set the stat parameter to identify the mode.
- fill : Represents color inside the bars.
- color : Represents color of outlines of the bars.
- width : Represents width of the bars.
Example: Consider a dataset that consists of information about the heights of five different students in a class. The height given in the data set is in feet. So, we need two Y-axes to represent the heights using the units "feet" and "centimeters."
First, we create a Data Frame which has two vectors "stud" containing students ID and "height" containing students height in feet and store it in a variable "height".
R
# Inserting data
height <- data.frame(stud=c("S-1","S-2","S-3",
"S-4","S-5"),
hght=c(4.7, 5.5, 4.9, 6.1,
6.4))
head(height)
Output:
Bar Plot
R
# Bar Plot
library(ggplot2)
plt <-ggplot(data=height, aes(x=stud, y=hght,fill=stud)) +
geom_bar(stat="identity")+
theme_classic()
plt
Output:

Adding Two Y-axes on either side
As scaling comes into the picture we have to use the R function scale_y_continuous( ) which comes in ggplot2 package. Also, another function sec_axis( ) is used to add a secondary axis and assign the specifications to it. The syntax is :
sec_axis(trans,name,breaks,labels,guide)
Parameters which we need :
trans : A formula or function needed to transform.
name : The name of the secondary axis.
Now, to transform the feet scale into centimeter-scale we need the scaling factor. To convert use :
1 feet = 30.48 cm
Now, in the trans argument inside the sec_axis( ) use the above scaling factor value and write the formula of conversion as shown below :
R
# Making two Y axes
plt+scale_y_continuous(
"feet",sec.axis=sec_axis(~.*30.48,name="centi meter"))
Output:
Similar Reads
Use different y-axes on the left and right of a Matplotlib plot
In this article, we are going to discuss how to create y-axes of both sides of a Matplotlib plot. Sometimes for quick data analysis, it is required to create a single graph having two data variables with different scales. For this purpose twin axes methods are used i.e. dual X or Y-axes. The matplot
2 min read
Combine two ggplot2 plots from different DataFrame in R
In this article, we are going to learn how to Combine two ggplot2 plots from different DataFrame in R Programming Language. Here in this article we are using a scatter plot, but it can be applied to any other plot. Let us first individually draw two ggplot2 Scatter Plots by different DataFrames then
2 min read
Changing Font Size and Direction of Axes Text in ggplot2 in R
In this article, we will discuss how to change the font size and the direction of the axis text using the ggplot2 plot in R Programming language. For both of the requirement theme() function is employed. After plotting a regular graph, simply adding theme() with appropriate values will get the job d
2 min read
Pie and Donut chart on same plot in ggplot2 using R
Visualizing categorical data using pie and donut charts can communicate proportions and distributions effectively. While pie charts show data in a circular layout divided into slices, donut charts add a "hole" in the center, providing a different visual perspective. In this article, we'll explore ho
4 min read
geom_area plot with areas and outlines in ggplot2 in R
An Area Plot helps us to visualize the variation in quantitative quantity with respect to some other quantity. It is simply a line chart where the area under the plot is colored/shaded. It is best used to study the trends of variation over a period of time, where we want to analyze the value of one
3 min read
How to plot a subset of a dataframe using ggplot2 in R ?
In this article, we will discuss plotting a subset of a data frame using ggplot2 in the R programming language. Dataframe in use: Â AgeScoreEnrollNo117700521880103177915419752051885256199630717903581971409188345 To get a complete picture, let us first draw a complete data frame. Example: R # Load ggp
9 min read
Change Space and Width of Bars in ggplot2 Barplot in R
In this article, we will see how to change the Space and width of bars in ggplot2 barplot in R. For Create a simple Barplot using ggplot2, first we have to load the ggplot2 package using the library() function. If you have not already installed then you can install it by writing the below command i
4 min read
Draw Plot with two Y-Axes in R
In this article, we are going to discuss how to create y-axes of both sides of a plot in R programming language. Sometimes for quick data analysis, it is required to create a single graph having two data variables with different scales. To do that in R language we use the following steps. First, we
3 min read
Transform ggplot2 Plot Axis to log Scale in R
In this article, we will discuss how to transform the ggplot2 Plot Axis to log Scale in the R Programming Language. Method 1: Using scale_x_continuous() function with trans argument We can convert the axis data into the desired log scale using the scale_x_continous() function. We pass the desired l
3 min read
How to add calibrated axes to PCA biplot in ggplot2 in R?
Principal Component Analysis (PCA) is the statistical technique used to emphasize the variation and bring out strong patterns in the dataset. It can be often used to reduce the dimensionality of the dataset while preserving as much variability as possible. the biplot is a type that can display the s
4 min read