Adding legend to a margin of a multiple for loop plot - r

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)

Related

How to plot legend in place of a plot multiple plots per window in R

I want to place a common legend for my three plots in the slot where the fourth plot would go (highlighted in yellow). How can I do this?
Code to reproduce plots
par(mfrow = c(2, 2))
x <- rep(1:9, 3)
y <- sample(1:9, 27, replace = T)
group <- rep(1:3, each = 9)
for(i in 1:3){
plot(x = x, y = y, type = "n")
for(j in 1:3){
print(c("red", "blue", "green")[group])
lines(x = x[group == j],
y = y[group == j],
col = c("red", "blue", "green")[j])
}
}
You can draw a "blank" plot in the last square and then draw the legend on top
for(i in 1:3){
plot(x = x, y = y, type = "n")
for(j in 1:3){
print(c("red", "blue", "green")[group])
lines(x = x[group == j],
y = y[group == j],
col = c("red", "blue", "green")[j])
}
}
plot(0, 0, type = 'l', bty = 'n', xaxt = 'n', yaxt = 'n', xlab="", ylab="")
legend('center',
legend = c("Red", "Blue", "Green"),
col = c("red","blue", "green"),
lwd=1, xpd = TRUE, cex = 1, seg.len=1, bty = 'n')

How to add % sign to Y axis?

I would like the numbers on the Y-axis to have a percent sign next to them. How would I go about doing this?
H <- c(61,89,94,89) # Create the data for the chart.#
M <- c("Pre-Calculus",
"College
Algebra",
"Intermediate
Algebra",
"Elementary
Algebra")
bp <- barplot(H, col =c("dodgerblue4" ), ylim = range(0,110),
names.arg = M, horiz = F,
family="Arial", border = NA, xlim = range(0,5), las=1,
axes = T, ylab = 'Passing Percent')
text(bp, H + 5, paste(H, "%", sep="")) #Automates data labels[![enter image description here][1]][1]
Override creation of y-axis with yaxt = 'n' and create a custom y-axis.
par(las=1)
bp <- barplot(H, col =c("dodgerblue4" ), ylim = range(0,110),
names.arg = M, horiz = F,
family="Arial", border = NA, xlim = range(0,5), las=1,
axes = T, ylab = 'Passing Percent', yaxt = "n")
val <- seq(0, 100, 20)
text(bp, H + 5, paste(H, "%", sep=""))
axis(2, at = val, labels = paste0(val, '%'))

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

Custom label on secondary y-axis in 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.

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

Resources