For a graph with 2 y axis in R, how do I add the label to the second y-axis?

Viewed 40

Goal: I'm trying to make a graph showing the water levels for a region over time that has two y axis (the first being the total megaliters of water in the water supply and the second being the dam capacity).

Problem: The title for my second y-axis isn't formatted correctly: it overlaps the increments on the y-axis and to the left of the values. I want to move it to the right.

Here's my code:

#data
years <- c(2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021)
levels <- c(646137, 450429, 279954, 190300, 191843, 411849, 481370, 626907)
percents <- c(71.9, 50.1, 31.2, 21.2, 21.4, 45.9, 53.6, 69.8)
allData <- data.frame(years, levels, percents)
levelsOverTime <- data.frame(years, levels)
percentsOverTime <- data.frame(years, percents)

#plot
plot(percentsOverTime, type="l", ylab="Water levels as percentages of dam capacity", main="Water Levels Over Time", xlab="Year", col="blue", ylim=c(0, 100))
par(new = TRUE)
plot(levelsOverTime, type="l", xaxt="n", yaxt="n", ylab="", xlab="", col="red", ylim=c(0, 650000))
axis(side = 4)
mtext("Total water stored in 6 major dams (megalitres)", side=4)
1 Answers

Try this way. You may change location of text using line = .

par(mar = c(5, 4, 4, 6) + 0.1)
plot(percentsOverTime, type="l", 
     main="Water Levels Over Time", xlab="", ylab = "", col="blue", ylim=c(0, 100), axes = FALSE)
axis(2, ylim = c(0,100), col = "blue", las = 1)
mtext("Water levels as percentages of dam capacity", side = 2, line = 2.5, col = "blue")
box()
par(new = TRUE)
plot(levelsOverTime, type="l", xaxt="n", yaxt="n", ylab="", xlab="", col="red", ylim=c(0, 650000), 
     axes = FALSE)
mtext("Total water stored in 6 major dams (megalitres)", side = 4, col = "red", line = 4)
axis(4, ylim = c(0, 650000), col = "red", las = 1)

axis(1, years)
mtext("Year", side = 1, col = "black", line = 2.5)

legend("bottomleft", legend = c("precents", "levels"),
       text.col = c("blue", "red"), col = c("black", "red"), lty = c(1,1))

enter image description here

par(mar = c(5, 4, 4, 6) + 0.1)
plot(percentsOverTime, type="l", 
     main="Water Levels Over Time", xlab="", ylab = "", col="blue", ylim=c(0, 100), axes = FALSE)
axis(2, ylim = c(0,100), col = "blue", las = 1)
mtext("Water levels as percentages of dam capacity", side = 2, line = 2.5, col = "blue")
box()
par(new = TRUE)
plot(levelsOverTime, type="l", xaxt="n", yaxt="n", ylab="", xlab="", col="red", ylim=c(0, 650000), 
     axes = FALSE)
mtext("Total water stored in 6 major dams (megalitres)", side = 4, col = "red", line = 4)
ytick <- seq(0, 650000, by = 100000)
axis(4, ylim = c(0, 650000), col = "red", las = 1, labels = format(ytick,scientific = FALSE), at = ytick)

axis(1, years)
mtext("Year", side = 1, col = "black", line = 2.5)

legend("bottomleft", legend = c("precents", "levels"),
       text.col = c("blue", "red"), col = c("black", "red"), lty = c(1,1))

enter image description here

Related