# Draw Plot with two Y-Axes in R

• Difficulty Level : Expert
• Last Updated : 29 Jun, 2021

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 create a sample data, such that the sample data consists of three numeric vectors: x, y1, and y2. The x data will determine X-axis information whereas y1 and y2 will be used for two Y-Axis simultaneously.

Now, we will create a scatter plot with two different colors and y-axis values on the left and right sides of the plot. To do so, firstly we will create white space around the plot. This leave space for second y-axis. This can be done using par() method. Now, create the first plot (i.e. the red cross dots) around the first Y-Axis that takes into account data y1.

Syntax:

plot(x, y1, pch , col )

Next, set new to TRUE in par() method. This needs to be called again after the first plot has been created. This tells the plot that a new plot will be drawn over the first one.

Syntax:

par(new = TRUE)

Next, plot the second plot now with taking y2 data in account.

Syntax:

plot(x, y2, pch = 15, col = 3, axes = FALSE, xlab = “”, ylab = “”)

Next set axis or any additional attribute if required.

Example:

## R

 `# Create sample data ` `set.seed``(2585)                            ` ` `  `x <- ``rnorm``(45) ` `y1 <- x + ``rnorm``(45) ` `y2 <- x + ``rnorm``(45, 7) ` ` `  `# Draw first plot using axis y1 ` `par``(mar = ``c``(7, 3, 5, 4) + 0.3)               ` `plot``(x, y1, pch = 13, col = 2)   ` ` `  `# set parameter new=True for a new axis ` `par``(new = ``TRUE``)          ` ` `  `# Draw second plot using axis y2 ` `plot``(x, y2, pch = 15, col = 3, axes = ``FALSE``, xlab = ``""``, ylab = ``""``) ` ` `  `axis``(side = 4, at = ``pretty``(``range``(y2)))       ` `mtext``(``"y2"``, side = 4, line = 3)`

Output:

Output

Example 2:

## R

 `# Create sample data ` `                           `  `x <- ``c``(1,2,3,4,5,6,7,8,9,10) ` `y1 <-``c``(2,5,2,8,6,8,3,4,2,4) ` `y2 <-``c``(2,5,3,7,5,9,7,9,4,1) ` ` `  `# Draw first plot using axis y1 ` `par``(mar = ``c``(7, 3, 5, 4) + 0.3)               ` `plot``(x, y1, type=``"l"``, col = 2)   ` ` `  `# set parameter new=True for a new axis ` `par``(new = ``TRUE``)          ` ` `  `# Draw second plot using axis y2 ` `plot``(x, y2, type=``"l"``, col = 3, axes = ``FALSE``, xlab = ``""``, ylab = ``""``) ` ` `  `axis``(side = 4, at = ``pretty``(``range``(y2)))       ` `mtext``(``"y2"``, side = 4, line = 3)`

Output:

My Personal Notes arrow_drop_up
Related Articles