Drawing an "arrow" in the R plot legend
I have a "curve" and a vertically positioned "arrow" in an R plot ( see R code below ).
I was wondering if an actual arrow could be shown in the "legend" rather than a smooth, straight line to distinguish my arrow from a curve?
Here is my R code:
curve(dnorm(x), -4, 4, lwd = 3)
arrows(2, 0, 2, .3, code = 2, lwd = 3, col = 'red4')
legend("topleft", legend = c("Curve", "Arrow"), lwd = 3, col = c(1, "red4"))
+3
source to share
2 answers
Something like this might work
windows(width = 6, height = 6)
curve(dnorm(x), -4, 4, lwd = 3)
arrows(2, 0, 2, .3, code = 2, lwd = 3, col = 'red4')
#Get the co-oridnates of extremes
extremes = par("usr")
#Determine how 'long' the lines should be in legend
xx = (extremes[2] - extremes[1])/16 #Change as necessary
yy = (extremes[4] - extremes[3])/16 #Change as necessary
#Draw lines and arrows
lines(x = c(extremes[1]+xx, extremes[1]+2*xx),
y = c(extremes[4]-yy, extremes[4]-yy),
lwd = 3)
arrows(x0 = extremes[1]+xx, x1 = extremes[1]+2*xx,
y0 = extremes[4]-2*yy, y1 = extremes[4]-2*yy,
code = 2,
lwd = 3,
col = 'red4')
#Labels for legend
lab = c("Line", "Arrow")
#Write labels in legend
text(x = c(extremes[1]+2*xx,extremes[1]+2*xx),
y = c(extremes[4]-yy, extremes[4]-2*yy),
labels = lab,
pos = 4)
#Maximum string width of labels
bx = max(strwidth(lab))*1.5
#Draw polygon
polygon(x = c(extremes[1], extremes[1]+2*xx+bx, extremes[1]+2*xx+bx, extremes[1]),
y = c(extremes[4], extremes[4], extremes[4]-(length(lab)+1)*yy, extremes[4]-(length(lab)+1)*yy))
+1
source to share
Here's how to put the right arrow in your legend instead of a string. You have to access font = 5 with par
to get the arrow symbol.
plot(1:10)
curve(dnorm(x), -4, 4, lwd = 3)
arrows(2, 0, 2, .3, code = 2, lwd = 3, col = 'red4')
legend("topleft", legend = c("Curve", "Arrow"),lwd = 3, col = c(1, "red4"),
lty=c(1,NA)) #normal legend. Do not plot line
par(font = 5) #change font to get arrows
legend("topleft", legend = c(NA,NA), pch=c(NA,174),lwd = 3,
col = c(1, "red4"),lty=c(1,NA),bty="n") #legend with font=5, only right arrow
par(font = 1) #back to default
+2
source to share