how to make the legend smaller? - r

I am trying to make the legend smaller. Why does the "upperleft" make the legend so big?Here are my codes. Thank you!
dnsm <- density(ecls$MATH5[ecls$GENDER_fac == "male"])
plot(dnsf,
col = "red",
xlab = "Fifth Grade Math Score",
main = "",
las = TRUE,
lwd = 2)
points(dnsm, col = "green", type = "l", lwd = 2)
legend(x = "topleft",
col = c("red", "green"),
legend = c("female", "male"),
lwd = 2)

Related

Plotting in the same graph and getting the same axis in R

I have been trying to plot my results in a graph. However, when watching the result I see that each have its own y-axis that does not correspond to the others. How could I possibly fix my problem?
RMSFE_AR <- c(0.380231, 0.3965452, 0.3408504, 0.398722)
RMSFE_RW <- c(0.492315, 0.4034821, 0.3671059, 0.3884792)
RMSFE_VAR <- c(0.429498, 0.4180072, 0.3546557, 0.4059629)
RMSFE_BVAR <- c(0.34, 0.3588872, 0.3510698, 0.3411622)
par(mfrow = c(1,1))
plot(RMSFE_AR, type = "l",
ylab = "", xlab = "", col = "red", lty = 2, xaxt="n", ylim=c(0.32,0.5))
axis(1, at = 1:4, labels = c("1", "3", "6", "12"))
par(new = TRUE)
plot(RMSFE_RW, type = "l",
ylab = "", xlab = "", col = "blue", lty = 2, axes=FALSE)
par(new = TRUE)
plot(RMSFE_VAR, type = "l",
ylab = "", xlab = "", col = "green", lty = 2, axes=FALSE)
par(new = TRUE)
plot(RMSFE_BVAR, type = "l",
ylab = "", xlab = "", col = "dark blue", lty = 2, axes=FALSE)
mtext("", side = 4, line = 3)
legend(par('usr')[1], par('usr')[3], bty='n', xpd=NA,cex = 0.7,
c("RMSFE AR(1)", "RMSFE RW", "RMSFE VAR", "RMSFE BVAR"),
col = c("red", "blue", "green", "dark blue"), lty = c(2, 2, 2, 2))
Create a data.frame, DF, from the data and col color vector and then use plot with type = "n" to set the appropriate ranges and then actually draw the lines using lines.
# inputs
DF <- data.frame("RMSFE AR(1)" = RMSFE_AR,
"RMSFE RW" = RMSFE_RW,
"RMSFE VAR" = RMSFE_VAR,
"RMSFE BVAR" = RMSFE_BVAR,
row.names = c(1, 3, 6, 12),
check.names = FALSE)
col <- c("red", "blue", "green", "dark blue")
x <- 1:nrow(DF)
plot(range(x), range(DF), type = "n", xlab = "", ylab = "", xaxt = "n")
axis(1, at = x, labels = rownames(DF))
for(i in 1:ncol(DF)) lines(DF[[i]], col = col[i], lty = 2)
legend("topright", legend = names(DF), bty = 'n', xpd = NA, cex = 0.7,
col = col, lty = 2)
or even easier using DF and col from above:
x <- 1:nrow(DF)
matplot(DF, lty = 2, type = "l", col = col, ylab = "", xaxt = "n")
axis(1, at = x, labels = rownames(DF))
legend("topright", legend = names(DF), bty = 'n', xpd = NA, cex = 0.7,
col = col, lty = 2)
You can use the following code:
plot(RMSFE_AR, type = "l",
ylab = "", xlab = "", col = "red", lty = 2, xaxt="n", ylim=c(0.32,0.5))
axis(1, at = 1:4, labels = c("1", "3", "6", "12"))
lines(RMSFE_RW, type = "l", col = "blue", lty = 2, axes=FALSE)
lines(RMSFE_VAR, type = "l", col = "green", lty = 2, axes=FALSE)
lines(RMSFE_BVAR, type = "l", col = "dark blue", lty = 2, axes=FALSE)
mtext("", side = 4, line = 3)
legend("topright", bty='n', xpd=NA,cex = 0.7,
c("RMSFE AR(1)", "RMSFE RW", "RMSFE VAR", "RMSFE BVAR"),
col = c("red", "blue", "green", "dark blue"), lty = c(2, 2, 2, 2))
Output:
Sorry, but it has to be done: You could use ggplot2.
library(ggplot2)
# reshape data so ggplot likes it
df <- data.frame(
var = rep(c("RMSFE_AR", "RMSFE_RW", "RMSFE_VAR", "RMSFE_BVAR"), each = 4),
x = rep(c(1,3,6,12), 4),
y = c(RMSFE_AR, RMSFE_RW, RMSFE_VAR, RMSFE_BVAR))
# make a plot
ggplot(df, aes(x = x, y = y, col = var)) +
geom_line(linetype = "longdash", size = 1) + # add line
scale_color_discrete(labels = c("RMSFE AR(1)", "RMSFE RW", "RMSFE VAR", "RMSFE BVAR")) + # rename legend items
labs(col = "", x = "", y = "") + # set legend and axis titles
theme_light() # prettier

How to set limits of grid in barplot?

I am trying to put grids in my barplots, but they appear in front of the data and not in the background. I tried to fix this using
panel.first = grid()
As for the data I am trying to plot, the first column consists of the year numbers (2014-2021) and the second columns are the corresponding values (all vector classes are numeric). When trying to plot using the following code:
par(mfrow=c(1,2))
barplot(mean_trend[,2],names.arg = mean_trend[,1],col="skyblue",ylim = c(0.1,95),cex=0.8,cex.names=0.85,las=2,cex.lab=0.85,lwd=1.5,panel.first = grid())
mtext(side=2,line=2.3, "Average amount in mm", font=2, cex=0.8)
box(lwd=1.5)
barplot(freq_trend[,2],names.arg = freq_trend[,1],col="skyblue",ylim = c(2,4500),cex=0.85,cex.names=0.85,las=2,cex.lab=0.85,lwd=1.5,panel.first = grid())
box(lwd=1.5)
mtext(side=2,line=3.3, "Average flood frequency", font=2, cex=0.8)
I obtain the following result
As you can see, the grid is now behind the plotted data, but exceeds the box/plot limits. How can I fix this?
Kind regards
As you didn't add a data mean_trend - I give an example with other data.
About add and others arguments - you can read ?barplot
# One row, two columns
par(mfrow = c(1, 2))
#PLOT1
barplot(table(mtcars$cyl), main = "PLOT 1", col = c("yellow", "green", "red"), ylim = c(0, 15))
grid(nx = NULL, ny = NULL, lwd = 1, lty = 1, col = "gray")
barplot(table(mtcars$cyl), col = c("yellow", "green", "red"), ylim = c(0, 15), add = TRUE)
#PLOT2
barplot(table(mtcars$cyl), main = "PLOT 2", col = c("yellow", "green", "red"), ylim = c(0, 15))
grid(nx = NULL, ny = NULL, lwd = 1, lty = 1, col = "gray")
barplot(table(mtcars$cyl), col = c("yellow", "green", "red"), ylim = c(0, 15), add = TRUE)

Save par(mfrow) multipanel output as svg

I'm using par(mfrow) to generate a multi-panel plot of three separate graph output objects. Sample code below represents a very simplified version of the objects I have.
How can I save these plots as a single object with ggsave? I've tried naming the par(mfrow) as an object and plotting it, but that doesn't seem to work.
Any advice on alternative ways of generating/saving a multi-panel plot is also welcome! Please let me know if I can clarify the question or example. Thanks!
par(mfrow = c(1,3), mar = c(10, 5, 5, 3), xpd = TRUE)
hist(x = rnorm(100), col = "skyblue", main = "X")
hist(x = rnorm(50), col = "green", main = "Y")
legend("bottom", c("Blue", "Green", "Purple"),
title = "Sample Data", horiz = TRUE, inset = c(0, -0.4),
col = c("skyblue", "green", "purple"), pch = rep(15,2),
bty = "n", pt.cex = 1.5, text.col = "black")
hist(x = rnorm(75), col = "purple", main = "Z")
I would suggest using svglite over svg if you want to edit the graph using Inkscape or a similar program since you will not be able to edit the text (change the text, font, or size) in a file produced by svg. Here is an example with a few edits to your original code:
library(svglite)
svglite("MyPlots.svg", width=8, height=6)
par(mfrow = c(1,3), mar = c(10, 5, 5, 3), xpd = TRUE, mgp=c(1.75, .75, 0))
hist(x = rnorm(100), col = "skyblue", main = "X")
hist(x = rnorm(50), col = "green", main = "Y")
legend("bottom", c("Blue", "Green", "Purple"),
title = "Sample Data", horiz = TRUE, inset = c(0, -0.2),
col = c("skyblue", "green", "purple"), pch = rep(15,2),
bty = "n", pt.cex = 1.5, text.col = "black")
hist(x = rnorm(75), col = "purple", main = "Z")
dev.off()

Making a dark theme plot in R

Let say I want to draw this function f(x) = x^2. I want the graph of the function to be any color I want and everything else (except the axis) black. Is this possbile?
graphics.off()
par(bg = "black")
curve(x^2, -2, 2, col = "green", axes = FALSE, ann = FALSE)
title("my plot", xlab = "X", ylab = "X^2", col.lab = "white", col.main = "white")
box(col = "white")
axis(1, seq(-2, 2, 1), seq(-2, 2, 1), col = "white", col.axis = "white")
axis(2, seq(0, 4, 1), seq(0, 4, 1), col = "white", col.axis = "white")
Maybe you can ?plot to see how to make it. Below is just an example
plot(x<-seq(-5,5,0.1),
x**2,
main="square function",
ylab="f(x)=x^2",
type="l",
col=28)

How to remove the zero labels in Histogram plot in R?

Any tips to remove the zero labels in between the histogram bars?
hist(links$Survey_Duration, breaks = seq(0,50,5), main = "Survey Duration",
labels = TRUE, border = "black",
xlab = "Survey", ylim = c(0, 15), col = "gray", las = 1, xaxt='n')
axis(side=1, at=seq(0,50,5), labels=seq(0,50,5))
abline(v = mean(links$Survey_Duration), col = "royalblue", lwd = 1.5)
abline(v = median(links$Survey_Duration), col = "red", lwd = 1.5)
legend(x = "topright", c("Mean", "Median"), col = c("royalblue","red"),
lwd = c(1.5,1.5))
How about this?
# modify data so there's zero in one of the bins
mtcars$mpg <- ifelse(mtcars$mpg >= 25 & mtcars$mpg <= 30, NA, mtcars$mpg)
# save plot parameters
h <- hist(mtcars$mpg, plot = FALSE)
# produce plot
plot(h, ylim = c(0, 14))
# add labels manually, recoding zeros to nothing
text(h$mids, h$counts + 1, ifelse(h$counts == 0, "", h$counts))
A slightly different answer using the labeling in hist instead of adding text afterwards.
You do not provide your data, so I will use some data that is handy to illustrate.
The labels argument can specify the individual labels
H1 = hist(iris$Sepal.Length, breaks = 3:8, plot=FALSE)
BarLabels = H1$counts
BarLabels[BarLabels == 0] = ""
hist(iris$Sepal.Length, breaks = 3:8, labels = BarLabels)
Thanks #Daniel Anderson, it Ok now (Thumbs Up)
links$Survey_Duration <- ifelse(links$Survey_Duration > 15 &
links$Survey_Duration <= 25,
NA,
links$Survey_Duration)
h <- hist(links$Survey_Duration, breaks = seq(0,50,5), plot = FALSE)
plot(h, ylim = c(0, 14), main = "Survey Duration", xlab = "Time", col = "gray", las = 1)
text(h$mids, h$counts + 1, ifelse(h$counts == 0, "", h$counts))
axis(side=1, at=seq(0,50,5), labels=seq(0,50,5))
abline(v = mean(links$Survey_Duration), col = "royalblue", lwd = 1.5)
abline(v = median(links$Survey_Duration), col = "red", lwd = 1.5)
legend(x = "topright",
c("Mean", "Median"),
col = c("royalblue","red"),
lwd = c(1.5,1.5))

Resources