Custom label on secondary y-axis in R - r

How can I put a custom label on the secondary y-axis in R using the following code?
library(zoo)
#--------------random data
x.Date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-"))
z <- zoo(rnorm(5), x.Date)
z2 <- zoo(rnorm(5, sd = 0.2), x.Date)
#--------------create plot
png(filename = "Google.png", width = 480, height = 480)
plot(z, type="l", xlab="Year", lt=1, lwd=1, ylab="Google Trend")
grid(nx = NULL, ny = NULL, col = "lightgray", lty = "dotted",
lwd = par("lwd"), equilogs = TRUE)
par(new=TRUE)
plot(z2, type="l", ann=FALSE, lt=1, lwd=3, yaxt="n")
axis(4, ylab="Test") # Here?!
legend("topright", c("z", "z2"), lty=c(1,1),
lwd=c(1,3),col=c("black","black"),
box.col="black",bg="white")
title("Google")
dev.off()
The label "Test" does not appear in my plot...
Furthermore, how to overwrite the gridlines with the z2 and the z lines? In other words, how to bring the plotted lines to the "front"?

You need mtext for this to work:
library(zoo)
#--------------random data
x.Date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-"))
z <- zoo(rnorm(5), x.Date)
z2 <- zoo(rnorm(5, sd = 0.2), x.Date)
#--------------create plot
#png(filename = "Google.png", width = 480, height = 480)
plot(z, type="l", xlab="Year", lt=1, lwd=1, ylab="Google Trend")
grid(nx = NULL, ny = NULL, col = "lightgray", lty = "dotted",
lwd = par("lwd"), equilogs = TRUE)
par(new=TRUE)
plot(z2, type="l", ann=FALSE, lt=1, lwd=3, yaxt="n")
axis(4)
#------here is the only part I added
#you specify the text, location and usually line=2 to place next to
#the y-axis labels
mtext('Test', side=4, line=2)
#-----------------------------------
legend("topright", c("z", "z2"), lty=c(1,1),
lwd=c(1,3),col=c("black","black"),
box.col="black",bg="white")
title("Google")
#dev.off()
Output:
As for z and z2 they dont seem to be behind the gridlines here.

Related

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

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)
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))
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))

Plot density lines without histogram

I want to plot density lines without showing the histogram, I used this code:
hist(www, prob=TRUE, xlab = "X", main = "Plot",xlim=c(0,11), ylim=c(0,1), breaks =100)
lines(density(x, adjust=5), col="red", lwd=2)
lines(density(y, adjust=5), col="blue", lwd=2)
lines(density(z, adjust=5), col="green", lwd=2)
And the result is showing in the the picture.
How can I remove the Histogram? Thank you in advance!
You could use plot(density(...)) instead of hist:
set.seed(123)
x <- rnorm(100, 0, 1)
y <- rnorm(100, 0.5, 2)
z <- rnorm(100, 1, 1)
dens <- lapply(list(x=x, y=y, z=z), density)
ran <- apply(do.call(rbind, sapply(dens, function(i) list(data.frame(x=range(i$x), y=range(i$y))))), 2, range)
plot(dens[[1]], xlim=ran[,1], ylim=ran[,2], type = 'n', main="Density")
lapply(seq_along(dens), function(i) lines(dens[[i]], col=i))
legend("topright", names(dens), col=seq_along(dens), lty=1)
Created on 2021-01-31 by the reprex package (v1.0.0)
Even easier is plotting with the ggplot2 package:
library(ggplot2)
dat <-data.frame(group=unlist(lapply(c("x", "y", "z"), function(i) rep(i, length(get(i))))),
value=c(x, y, z))
ggplot(dat, aes(x=value, colour=group))+
geom_density()
Using three toy vectors, try this:
x <- rnorm(100, 0, 1)
y <- rnorm(100, 0.5, 2)
z <- rnorm(100, 1, 1)
plot(density(x, adjust = 5), col = "red", lwd = 2,
xlim = c(-20, 20), ylim = c(0, 0.25), xlab = "X")
par(new=T)
plot(density(y, adjust = 5), col = "blue", lwd = 2,
xlim = c(-20, 20), ylim = c(0, 0.25), xlab = "")
par(new=T)
plot(density(z, adjust = 5), col = "green", lwd = 2,
xlim = c(-20, 20), ylim = c(0, 0.25), xlab = "")
You will need to adjust xlim and ylim in the right way

X Axis not showing up R

I am trying to use two different Y axis with the same X Axis and when I set both axes to false the Year wont show up
library(lubridate)
x <- dataset$Date
y <- dataset$AvgCostPerKwh
z <- dataset$ActualkWhSold
par(mar=c(5, 4, 4, 6) + 0.1)
plot(year(x),y, pch = 16, axes = FALSE, ylim = c(0.030,0.090), xlab = "", ylab = "",
type = "b", col="black", main = "Wholesale Power cost")
axis(2, ylim =(range(c(y))), col = "black", las =1)
mtext("$ per KWh", side = 2, line = 2.5)
box()
par(new = TRUE)
plot(year(x),z, pch = 15, xlab = "", ylab = "",ylim=c(5000000,45000000),
axes = FALSE, type="b", col="red")
mtext("Kwh's Sold", side=4, col="red", line=4)
axis(4, ylim=(range(c(z))), col = "red", las=1)
mtext("Year", side = 1, col="black",line=2.5)
legend("topleft", legend = c("AvgCostPerKwh", "ActualKwhSold"),
text.col = c("black", "red"),
pch=c(15,15),col=c("black", "red"))
Image 1
When I set one of the plots to true, I get overlapping values one one side, but the year on the bottom shows up.
library(lubridate)
x <- dataset$Date
y <- dataset$AvgCostPerKwh
z <- dataset$ActualkWhSold
par(mar=c(5, 4, 4, 6) + 0.1)
plot(year(x),y, pch = 16, axes = TRUE, ylim = c(0.030,0.090), xlab = "", ylab = "",
type = "b", col="black", main = "Wholesale Power cost")
axis(2, ylim =(range(c(y))), col = "black", las =1)
mtext("$ per KWh", side = 2, line = 2.5)
box()
par(new = TRUE)
plot(year(x),z, pch = 15, xlab = "", ylab = "",ylim=c(5000000,45000000),
axes = FALSE, type="b", col="red")
mtext("Kwh's Sold", side=4, col="red", line=4)
axis(4, ylim=(range(c(z))), col = "red", las=1)
mtext("Year", side = 1, col="black",line=2.5)
legend("topleft", legend = c("AvgCostPerKwh", "ActualKwhSold"),
text.col = c("black", "red"),
pch=c(15,15),col=c("black", "red"))
image 2
I am not sure, I have followed other examples on here about 2 Y axis and I can't get mine to work.
I have answered my own question for anyone interested, I forgot to add
year(as.Date(dataset$Date, format = "%m/%d/%Y"),"%Y")
at the top before adding
plot(year(x), y, pch=16, axes=FALSE, ylim=c(0.030,1), xlab="", ylab="",
type="b",col="black", main="Wholesale Power Cost")

Axis cut off in multiple plot figure in R

I am using layout() to create a multiple plot figure in R and only want the y-axis to show up in the bottom plots. I therefore take them out of the loop and add them in below with the axes, but when I do this, they get cut off. Here is the code I'm using:
onlytext <- function(string){
plot(0:1, 0:1, bty='n', type='n', xaxt='n', yaxt='n', xlab='', ylab='')
text(0.5, 0.5, string, cex=1.2, font=2)
}
nf <- layout(matrix(c(0,1:14), 5, 3, byrow=TRUE), heights = c(2,5,5,5,5), widths = c(1.5,4,4))
par (mar=c(.3,.3,.3,.3))
onlytext ('Approval'); onlytext ('Vote Choice')
name_vec <- c("Strongly Approve", "Approve", "Disapprove", "Strongly Disapprove")
control_means_tab <- matrix(sample(rnorm(100), 48), ncol = 6, nrow = 4)
x <- seq(1,6)
for(i in 1:3){
onlytext(name_vec[i])
for(j in 1:2){
plot(x, control_means_tab[j,], xaxt = 'n', xlab = '', ylab = '', xaxt='n', bty = "n", ylim = c((min(c(control_means_tab, scorecard_means_tab, endorsement_means_tab))- .02),(max(c(control_means_tab, scorecard_means_tab, endorsement_means_tab)) + .02)), col = "blue", pch = 19, cex =.6)
}
}
onlytext(name_vec[4])
plot(x, control_means_tab[j,], xlab = '', ylab = '', xaxt = "n", bty = "n", ylim = c((min(c(control_means_tab, scorecard_means_tab, endorsement_means_tab))- .02),(max(c(control_means_tab, scorecard_means_tab, endorsement_means_tab)) + .02)), col = "blue", pch = 19, cex =.6)
axis(1, 1:6, LETTERS[1:6])
plot(x, control_means_tab[j,], xaxt = 'n', xlab = '', ylab = '', xaxt='n', bty = "n", ylim = c((min(c(control_means_tab, scorecard_means_tab, endorsement_means_tab))- .02),(max(c(control_means_tab, scorecard_means_tab, endorsement_means_tab)) + .02)), col = "blue", pch = 19, cex =.6)
axis(1, 1:6, LETTERS[1:6])
Any thoughts on how to get that axis back is is appreciated!
I couldn't get the ylim part of you code to work, since you didn't provide information on scorecard_means_tab or endorsement_means_tab, but I think I see what you're after, in general. Give this code a try and see if it helps.
x <- seq(1, 6)
y <- matrix(sample(rnorm(100), 48), ncol=6, nrow=8)
ylabs <- rep(c("Strongly Approve", "Approve", "Disapprove", "Strongly Disapprove"), rep(2, 4))
xlabs <- rep(c("Approval", "Vote Choice"), 4)
par(mfrow=c(4, 2), mar=c(1, 1, 1, 1), oma=c(2, 4, 2, 1))
for(i in seq(dim(y)[1])) {
if(i < 6.5) {
plot(x, y[i, ], xaxt='n', xlab='', ylab='', bty="n", col="blue", pch=19, cex=0.6)
} else {
plot(x, y[i, ], xlab='', ylab='', bty="n", col="blue", pch=19, cex=0.6)
}
if(i < 2.5) mtext(xlabs[i], side=3, line=1)
if(i %in% c(1, 3, 5, 7)) mtext(ylabs[i], side=2, line=3)
}

Adding legend to a margin of a multiple for loop plot

This is perhaps an old question, but I can't find a satisfactory answer anywhere. Say that I have a following code:
par(mfrow = c(2,1), mar = c(4,4,1,1), oma=c(2,2,2,2))
stuff <- c("ed", "bla")
cols <- c("red", "blue")
for(i in 1:length(stuff)) {
x <- rnorm(10,3,2)
y <- seq(1,10)
plot(x,y, type = "o", col = cols[i], xlab = paste("stuff about", stuff[i]))}
legend("bottomright", legend = stuff, col = cols, lwd = 1, bty = "n")
par(mfrow=c(1,1))
title(main = "ed & bla", outer = T)
mtext("This is a plot", 3, line=0.5, adj=1.0, cex=1, outer=TRUE)
How can I add the legend in the bottom margin of the plot?
Re-order the plot requests, so that you plot the legend immediately after the last plot (outside the loop) but before the next modification to the plot parameters. Note that only the "legend" command has been moved:
par(mfrow = c(2,1), mar = c(4,4,1,1), oma=c(2,2,2,2))
stuff <- c("ed", "bla")
cols <- c("red", "blue")
for(i in 1:length(stuff)) {
x <- rnorm(10,3,2)
y <- seq(1,10)
plot(x,y, type = "o", col = cols[i], xlab = paste("stuff about", stuff[i]))}
legend("bottomright", legend = stuff, col = cols, lwd = 1, bty = "n")
par(mfrow=c(1,1))
title(main = "ed & bla", outer = T)
mtext("This is a plot", 3, line=0.5, adj=1.0, cex=1, outer=TRUE)
This puts the legend into the bottom-right of the bottom plot.
but you have to set the coordinate manualy
par(mfrow = c(2,1), mar = c(4,4,1,1), oma=c(2,2,2,2))
stuff <- c("ed", "bla")
cols <- c("red", "blue")
for(i in 1:length(stuff)) {
x <- rnorm(10,3,2)
y <- seq(1,10)
plot(x,y, type = "o", col = cols[i], xlab = paste("stuff about", stuff[i]))}
legend(y=-5, x=5, legend = stuff, col = cols, lwd = 1, bty = "n", xpd=NA)

Resources