Search code examples
rplotscatter-plot

Scatterplot with 2 y-axis in R


I have the following data in my dataset named "px"

anneemut valeurfonc sbati
2014 696300 321.5
2015 426600 144.5
2016 510000 163.0

And some other years.

I'd like to plot this 3 variables in the same chart. I thought about a scatter plot, with y1 = anneemut and y2 = sbati.

I found this code online :

par(mar = c(5, 4, 4, 4) + 0.3)   # Additional space for second y-axis
plot(px$valeurfonc, px$anneemut, pch = 16, col = 2)              

# Create first plot
par(new = TRUE)                 # Add new plot
plot(px$anneemut, px$sbati, pch = 17, col = 3,  

# Create second plot without axes
     axes = FALSE, xlab = "", ylab = "")
axis(side = 4, at = pretty(range(px$sbati)))      
# Add second axis
mtext("Avg_surface", side = 4, line = 3)

Here is the output enter image description here

I cannot manage to change the name of my axis. I tried to do

# Create second plot without axes
     axes = FALSE, xlab = "Price", ylab = "Year")

But the initial names don't disappear and then we can't read anything.

Furthermore, I cannot manage to add all the year in the first y axis, and all the values, in full number, in the x-axis.

Is there a way to do this in ggplot for instance ?


Solution

  • You can use the following code:

    px <- data.frame(anneemut = c(2014, 2015, 2016),
                     valuerfonc = c(696300, 426600, 510000),
                     sbati = c(321.5, 144.5, 163.0))
    
    par(mar = c(5, 4, 4, 4) + 0.3)              
    plot(px$valuerfonc, px$anneemut, xlab = "valuerfonc", ylab = "anneemut", pch = 16, col = 2)              
    par(new = TRUE)                             
    plot(px$valuerfonc, px$sbati, pch = 17, col = 3,              
         axes = FALSE, xlab = "", ylab = "")
    axis(side = 4, at = pretty(range(px$sbati)))      
    mtext("sbati", side = 4, line = 3) 
    

    Created on 2022-07-01 by the reprex package (v2.0.1)