我在 R 图中有一个“曲线”和一个直立定位的“箭头”(请参阅下面的 R 代码)。
我想知道是否有可能在“图例”中显示一个实际的箭头而不是一条平滑的直线来区分我的箭头和曲线?
这是我的 R 代码:
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"))
Run Code Online (Sandbox Code Playgroud)
以下是如何在图例中放置右箭头来代替线条。您必须访问 font = 5 才能par获得箭头符号。
curve(dnorm(x), -4, 4, lwd = 3)
arrows(2, 0, 2, .3, code = 2, lwd = 3, col = 'red4')
legend("topleft", legend = c("Curve", "Arrow"), pch = c(NA, NA),
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")
par(font = 1) #back to default
Run Code Online (Sandbox Code Playgroud)
像这样的东西可能会起作用
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))
Run Code Online (Sandbox Code Playgroud)